<template>
  <div id="create-plan">
    <!-- 计划信息设置 -->
    <div class="plan-card">
      <div class="plan-card-header">
        <div class="title">计划信息设置</div>
      </div>
      <div class="plan-card-content other-style">
        <!-- 计划信息设置  form 表单 -->
        <el-form
          class="planInformation-card"
          :model="salesPlanForm"
          :rules="planInformationRules"
          ref="salesPlanForm"
        >
          <!-- 计划名称 -->
          <el-form-item label="计划名称：" prop="planName">
            <el-input
              type="text"
              size="small"
              placeholder="请输入计划名称"
              class="planInfo-input"
              v-model="salesPlanForm.planName"
            ></el-input>
          </el-form-item>
          <!-- 店铺名称 -->
          <el-form-item label="店铺名称：" prop="shopId">
            <el-select
              size="small"
              placeholder="请输入店铺名称"
              class="planInfo-input"
              v-model="salesPlanForm.shopId"
              filterable
              :filter-method="dataFilter"
              @change="changeShop"
            >
              <el-option
                v-for="(value, index) in shopNameList"
                :key="index"
                :label="value.name"
                :value="value.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 店铺种类 -->
          <el-form-item label="店铺种类：" prop="shopType">
            <el-select
              type="text"
              size="small"
              placeholder="请输入店铺种类"
              class="planInfo-input"
              v-model="salesPlanForm.shopType"
            >
              <el-option
                v-for="(item, index) in platformTypeList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 入口类型 -->
          <el-form-item label="入口类型：" prop="entranceType">
            <el-select
              :disabled="isForbidModify"
              v-model="salesPlanForm.entranceType"
              placeholder="请选择入口类型"
              size="small"
              class="planInfo-input"
              @change="
                (val) => {
                  // 选择路口类型后再次更新视图
                  entranceTypeChange(val, salesPlanForm);
                }
              "
            >
              <el-option
                v-for="(item, index) in entranceTypeList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 二维码 -->
          <el-form-item
            v-if="salesPlanForm.entranceType == 3"
            label="二维码："
            prop="keyword"
          >
            <img
              :src="salesPlanForm.keyword"
              alt=""
              v-if="salesPlanForm.keyword && isForbidModify"
            />

            <div class="qrcode-img-box" v-else>
              <!-- 点击上传图片 -->
              <el-upload
                class="upload-box"
                :action="BASE_API_URL + 'baseapi/wechart/uploadMerchantPushImg'"
                :data="uploadQrcodeData"
                :show-file-list="false"
                :on-success="qrcodeSuccess"
                :before-upload="qrcodeBeforeAvatarUpload"
              >
                <img
                  v-if="salesPlanForm.keyword"
                  :src="salesPlanForm.keyword"
                  class="avatar"
                />
                <i v-else class="upload-icon el-icon-ali-upload"></i>
              </el-upload>
            </div>
          </el-form-item>
          <!-- 关键词 等等 -->
          <el-form-item
            v-else
            :label="entranceTypeName[salesPlanForm.entranceType] + ':'"
            prop="keyword"
          >
            <el-input
              class="planInfo-input"
              type="textarea"
              size="small"
              @blur="expressionFilter(salesPlanForm)"
              @input="inputUpdate($event)"
              autosize
              :disabled="isForbidModify"
              placeholder="请输入内容"
              v-model="salesPlanForm.keyword"
            ></el-input>
          </el-form-item>
          <!-- 销量任务 -->
          <el-form-item class="center-cell" label="任务数量:" prop="taskNum">
            <el-input
              class="planInfo-input"
              type="text"
              size="small"
              :disabled="isForbidModify"
              @input="inputUpdate($event)"
              onKeypress="return(/[\d]/.test(String.fromCharCode(event.keyCode)))"
              placeholder="请输入内容"
              v-model="salesPlanForm.taskNum"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 商品信息设置 -----  -->
    <div class="plan-card" v-if="hideOrShow">
      <div class="plan-card-header">
        <div class="title">商品信息设置</div>
      </div>
      <div class="plan-card-content">
        <!-- 循环生成添加、删除模块 -->
        <div
          class="task-card"
          v-for="(value, index) in salesPlanForm.planMessage"
          :key="index"
        >
          <!-- 左侧表单 -->
          <div>
            <!-- 商品信息表单 -->
            <el-form
              ref="goodsInfoForm"
              :model="value"
              :rules="goodsRules"
              label-width="120px"
              class="goods-form"
            >
              <!-- 商品链接 -->
              <el-form-item label="商品链接:" prop="goodsUrl">
                <el-input
                  placeholder="请输入商品链接"
                  v-model="value.goodsUrl"
                  size="small"
                  :disabled="isForbidModify"
                  class="form-input"
                  @blur="changeGoodsUrl(index)"
                ></el-input>

                <!-- 右侧按钮 -->
                <div style="display: inline-block" v-if="!isForbidModify">
                  <el-button
                    class="form-btn"
                    @click="grabGoodsInfo(index)"
                    v-if="!isWphUrl"
                  >抓取商品信息</el-button
                  >
                  <div class="form-btn-tips" v-else>唯品会需要手动输入</div>
                  <el-button
                    class="form-btn"
                    @click="showSelectGoodsDialog(index)"
                  >选择商品</el-button
                  >
                </div>
              </el-form-item>

              <!-- 商品id -->
              <el-form-item label="商品id:" prop="productId">
                <el-input
                  placeholder
                  v-model="value.productId"
                  size="small"
                  :disabled="true"
                  class="form-input"
                ></el-input>
              </el-form-item>

              <!-- 商品标题 -->
              <el-form-item label="商品标题:" prop="goodsTitle">
                <el-input
                  :disabled="isForbidRevise"
                  placeholder="请输入商品标题"
                  v-model="value.goodsTitle"
                  size="small"
                  class="form-input"
                ></el-input>
              </el-form-item>

              <!-- 店铺名称 -->
              <el-form-item label="店铺名称:" prop="shopName">
                <el-input
                  :disabled="isForbidRevise"
                  type="text"
                  size="small"
                  placeholder="请输入店铺名称"
                  class="form-input"
                  v-model="value.shopName"
                >
                </el-input>
              </el-form-item>

              <!-- 每单拍 -->
              <el-form-item label="每单拍:" prop="buyNum">
                <el-input
                  type="text"
                  size="small"
                  :disabled="isForbidModify"
                  placeholder="请输入内容"
                  v-model="value.buyNum"
                  class="form-input"
                  @input="inputUpdate($event)"
                  onKeypress="return(/[\d]/.test(String.fromCharCode(event.keyCode)))"
                ></el-input>
              </el-form-item>

              <!-- 拍下规格 -->
              <el-form-item label="拍下规格:" prop="sku">
                <el-input
                  type="text"
                  size="small"
                  :disabled="isForbidModify"
                  placeholder="请输入拍下规格"
                  v-model="value.sku"
                  class="form-input"
                  @input="inputUpdate($event)"
                ></el-input>
              </el-form-item>

              <!-- 拍下单价 -->
              <el-form-item label="拍下单价:" prop="payMoney">
                <el-input
                  type="text"
                  size="small"
                  :disabled="isForbidModify"
                  placeholder="请输入拍下规格"
                  v-model="value.payMoney"
                  @input="inputUpdate($event)"
                  class="form-input"
                ></el-input>
              </el-form-item>
              <!-- 条件渲染 -->
              <!-- 掌柜昵称 -->
              <el-form-item
                label="掌柜昵称 :"
                prop="goodsSeller"
                v-if="value.shopType == 1 || value.shopType == 2"
              >
                <el-input
                  placeholder
                  :disabled="isForbidRevise"
                  v-model="value.goodsSeller"
                  class="form-input"
                  size="small"
                  clearable
                ></el-input>
              </el-form-item>

              <div class="other-info">
                <!-- 搜索展示价格 -->
                <el-form-item
                  label="搜索展示价格 :"
                  class="set-error-msg"
                  prop="showMoney"
                >
                  <el-input
                    type="number"
                    v-model.number="value.showMoney"
                    auto-complete="off"
                    size="small"
                    class="other-info-input"
                    :disabled="isForbidModify"
                  ></el-input>
                </el-form-item>

                <!-- 付款人数约 -->
                <el-form-item label="付款人数约:" prop="payPerson">
                  <el-input
                    type="number"
                    v-model.number="value.payPerson"
                    onKeypress="return(/[\d]/.test(String.fromCharCode(event.keyCode)))"
                    auto-complete="off"
                    size="small"
                    class="other-info-input"
                    :disabled="isForbidModify"
                  ></el-input>
                </el-form-item>

                <!-- 条件渲染 -->
                <!-- 商品归属地 -->
                <el-form-item
                  label="商品归属地:"
                  prop="goodsAddress"
                  v-if="value.shopType == 1 || value.shopType == 2"
                >
                  <el-input
                    v-model="value.goodsAddress"
                    auto-complete="off"
                    size="small"
                    class="other-info-input"
                    :disabled="isForbidModify"
                  ></el-input>
                </el-form-item>
              </div>
            </el-form>
          </div>

          <!-- 商品大图 -->
          <div class="goods-img-box">
            <div class="goods-img" v-if="value.goodsImg && isForbidModify">
              <img :src="value.goodsImg" alt="" />
              <p>商品主图</p>
            </div>

            <div class="goods-img" v-else>
              <el-upload
                class="avatar-uploader"
                :action="BASE_API_URL + 'baseapi/wechart/uploadMerchantPushImg?index='+ index "
                :data="uploadData"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="value.goodsImg"
                  :src="value.goodsImg"
                  class="avatar"
                />
                <i v-else class="upload-icon el-icon-ali-upload"></i>
              </el-upload>
              <p>商品主图</p>
            </div>
          </div>

          <!-- 添加、删除 -->
          <div class="task-card-right" v-if="!isForbidModify">
            <i
              class="cut-task-icon el-icon-ali-cut"
              @click="cutTask(index)"
              v-if="salesPlanForm.planMessage.length != 1"
            ></i>
            <span v-if="isShowAddButton">
              <i
                class="add-task-icon el-icon-ali-add"
                @click="addTask"
                v-if="index == salesPlanForm.planMessage.length - 1"
              ></i>
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 发布时间设置 ------  -->
    <div class="plan-card" v-if="hideOrShow">
      <div class="plan-card-header">
        <div class="title">发布时间设置</div>
        <div class="tips">*开始时间不能大于结束时间！</div>
      </div>
      <div class="plan-card-content">
        <div class="time-type-box">
          <div class="title">设置类型：</div>
          <div class="tabs-nav" :class="isForbidModify ? 'disabled-click' : ''">
            <div
              class="tab"
              :class="salesPlanForm.allotType == item.type ? 'active' : ''"
              v-for="(item, index) in tabsList"
              :key="index"
              @click="changeTimeTab(item.type)"
            >
              {{ item.name }}
            </div>
          </div>
        </div>
        <div class="set-time-box">
          <div class="title">设置时间：</div>
          <div class="time-select-box" v-if="salesPlanForm.allotType == 1">
            <el-date-picker
              v-model="setPlanTime.startTime"
              :disabled="isForbidModify"
              :picker-options="pickerOptions1"
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
              @change="changeDate"
            ></el-date-picker>
            ~
            <el-date-picker
              type="datetime"
              :disabled="isForbidModify"
              placeholder="选择日期时间"
              :picker-options="pickerOptions1"
              value-format="timestamp"
              v-model="setPlanTime.endTime"
              @change="changeDate"
            ></el-date-picker>
            <el-checkbox
              class="check-box"
              :disabled="isForbidModify"
              v-model="salesPlanForm.planOver"
              :true-label="1"
              :false-label="2"
            >设置计划终止时间:</el-checkbox
            >
            <el-date-picker
              type="datetime"
              :picker-options="pickerOptions1"
              placeholder="选择日期时间"
              value-format="timestamp"
              v-model="salesPlanForm.planOver == 2 ? '' : setPlanTime.overTime"
              :disabled="salesPlanForm.planOver == 2 ? true : false"
              @change="changeOverTime"
            ></el-date-picker>
          </div>
          <div class="time-select-box" v-else-if="salesPlanForm.allotType == 2">
            <el-date-picker
              v-model="setPlanTime.startTime"
              :disabled="isForbidModify"
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
              @change="changeManualAllocationTime"
              @blur="selectDate"
            ></el-date-picker>
            ~
            <!--  <el-date-picker type="datetime" placeholder="选择日期时间" :picker-options="pickerOptions1" value-format="timestamp" v-model="setPlanTime.endTime" @change="changeManualAllocationEndTime" @blur="selectDate"></el-date-picker>-->
            <el-date-picker
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
              v-model="setPlanTime.endTime"
              @change="changeManualAllocationEndTime"
              @blur="selectDate"
            ></el-date-picker>
            <el-checkbox
              class="check-box"
              :disabled="isForbidModify"
              v-model="salesPlanForm.planOver"
              :true-label="1"
              :false-label="2"
            >设置计划终止时间:</el-checkbox
            >
            <el-date-picker
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
              v-model="salesPlanForm.planOver == 2 ? '' : setPlanTime.overTime"
              :disabled="salesPlanForm.planOver == 2 ? true : false"
              @change="changeOverTime"
            ></el-date-picker>
          </div>
          <div class="time-select-box" v-else>
            <el-date-picker
              v-model="setPlanTime.startTime"
              :disabled="isForbidModify"
              :picker-options="pickerOptions2"
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
              @change="changeStartTime"
            ></el-date-picker>
            <el-checkbox
              class="check-box"
              :disabled="isForbidModify"
              v-model="salesPlanForm.planOver"
              :true-label="1"
              :false-label="2"
            >设置计划终止时间:</el-checkbox
            >
            <el-date-picker
              type="datetime"
              :picker-options="pickerOptions2"
              placeholder="选择日期时间"
              value-format="timestamp"
              v-model="salesPlanForm.planOver == 2 ? '' : setPlanTime.overTime"
              :disabled="salesPlanForm.planOver == 2 ? true : false"
              @change="changeOverTime"
            ></el-date-picker>
          </div>
        </div>
        <div class="set-number" v-if="salesPlanForm.allotType == 2">
          <div class="title">数量设置：</div>
          <el-collapse>
            <div
              class="set-n-row"
              v-for="(item, key, index) in salesPlanForm.planTime"
              :key="index"
            >
              <el-collapse-item>
                <template slot="title">
                  <div>
                    <el-tag>{{ getMonthAndDay(parseInt(key)) }}</el-tag>
                  </div>
                </template>
                <div>
                  <div
                    class="plan-time-box"
                    v-for="(subItem, subKey, subIndex) in item"
                    :key="subIndex"
                  >
                    <div class="time">
                      {{ getDateOfHours(parseInt(subKey)) }}:00
                    </div>
                    <el-input-number
                      :disabled="isForbidEditNum"
                      :min="0"
                      v-model="item[subKey]"
                      controls-position="right"
                      @change="changeAllotNum(item, subKey)"
                    ></el-input-number>
                  </div>
                </div>
              </el-collapse-item>
            </div>
          </el-collapse>
          <div class="count-number">
            <span
            >计划中单数:<span>{{ countIntendOrderNum() }}</span
            >&nbsp;,&nbsp;</span
            >
            <span
            >已分配总计:<span>{{ totalAllotNum }}</span></span
            >
          </div>
        </div>
        <div class="remark-box">
          <div class="remark-example-box" v-if="!isForbidModify">
            <div
              class="remark-example"
              @click="clickRemarkText(rm.remark)"
              v-for="(rm, rmIndex) in remarkList"
              :key="rmIndex"
            >
              {{ rm.remark }}
            </div>
          </div>
          <div class="textarea-box">
            <span class="title">*</span>商家要求(150字以内)：
            <el-input
              type="textarea"
              :disabled="isForbidModify"
              placeholder="请输入内容"
              style="width: 500px"
              v-model="salesPlanForm.remark"
              maxlength="150"
            ></el-input>
          </div>
        </div>
      </div>
    </div>

    <!-- 问答设置 -->
    <!-- <div
      class="plan-card"
      v-if="
        showCheckContentArr.indexOf(salesPlanForm.shopType) >= 0 &&
        checkContentStatus
      "
    >
      <div class="plan-card-header">
        <div class="title">问答设置</div>
        <div class="tips">
          *请从该商品的商品详情页提取连续5个字，作为推手验证的文本！！
        </div>
      </div>
      <div class="plan-card-content">
        <div class="tips">注：此文本必须醒目，否则将导致任务无法完成</div>
        <div class="check-content-box">
          <span class="title">商品详情页连续5个字文本 :</span>
          <el-input
            class="input"
            :disabled="isForbidModify"
            placeholder="请输入商品详情页文本"
            @blur="getCheckContentText"
            maxlength="5"
            v-model="salesPlanForm.checkContent"
            size="small"
          ></el-input>
          <span
            >注： 推手需提交中间的文字去验证：<span class="tips">{{
              checkContent
            }}</span></span
          >
        </div>
      </div>
    </div> -->

    <!-- 按钮 -->
    <div class="page-footer">
      <el-button class="show-pay-info-btn" @click="creatPlanButton">{{
          planType == "pay" ? "支付计划" : "创建计划"
        }}</el-button>
    </div>

    <!-- 弹窗1 选择商品-->
    <el-dialog
      title="选择商品"
      :visible.sync="isShowGoodsDialog" :modal-append-to-body="false"
      width="950px"
      class="dialog-style select-goods-modal"
    >
      <div class="select-goods-modal-header">
        <el-form>
          <el-form-item label="店铺类型：">
            <el-select
              v-model="goodsSelect.shopType"
              placeholder="请选择店铺"
              size="small"
            >
              <el-option label="全部" value=""></el-option>
              <el-option
                v-for="(item, index) in platformTypeList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="店铺名称：">
            <el-select
              v-model="goodsSelect.shopId"
              placeholder="请选择店铺"
              size="small"
            >
              <el-option label="全部" value=""></el-option>
              <el-option
                v-for="(item, index) in shopNameList"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品ID：">
            <el-input
              size="small"
              placeholder="请输入商品ID"
              v-model="goodsSelect.productId"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item style="width: 100px">
            <el-button
              class="inquire-btn"
              icon="el-icon-ali-search"
              @click="searchGoodsData"
            >查询</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="select-goods-modal-content">
        <div
          class="goods-img-box"
          v-for="(item, index) in goodsList"
          :key="index"
          :class="curSelectGoodsIndex == item.id ? 'selectStyle' : ''"
          @click="selectGoods(item, item.id)"
        >
          <img class="goods-img" :src="item.goods_img" alt="" />
          <div class="text">店铺名称:{{ item.shop_name }}</div>
          <div class="text">商品ID:{{ item.product_id }}</div>
        </div>
        <div class="no-data-img" v-if="goodsList.length == 0">
          <img src="../../assets/image/no-data.png" alt="" />
          <div class="tips">暂无数据</div>
        </div>
      </div>
      <!-- 按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button class="cancel-btn" @click="isShowGoodsDialog = false"
        >取消</el-button
        >
        <el-button class="submit-btn" @click="sumbitSelectGoods(curSelectGoods)"
        >确认</el-button
        >
      </div>
    </el-dialog>

    <!-- 弹窗2 选择投放区域 -->
    <el-dialog :modal-append-to-body="false"
               title="选择投放区域"
               :visible.sync="isShowAreaDialog"
               width="900px"
               class="area-dialog"
    >
      <template>
        <div class="tips">*默认全部地区投放（不投放地区可以去掉勾选）</div>
        <div class="area-content">
          <div
            class="province-select"
            v-for="(item, index) in provinceOpitons"
            :key="index"
          >
            <div class="left-box">
              <el-checkbox
                :indeterminate="item.isIndeterminate"
                v-model="item.checkAll"
                @change="handleCheckAllChange($event, item)"
              >{{ item.area }}</el-checkbox
              >
            </div>
            <div style="display: inline-block">
              <el-checkbox-group
                v-model="item.checkedCities"
                @change="handleCheckedProvinceChange($event, item)"
              >
                <el-checkbox
                  v-for="city in item.province"
                  :label="city"
                  :key="city"
                >{{ city }}</el-checkbox
                >
              </el-checkbox-group>
            </div>
          </div>
        </div>
      </template>
      <span slot="footer" class="dialog-footer" style="position: relative">
        <div class="save-btn">
          <el-button @click="saveAreaData">保存设置</el-button>
        </div>
      </span>
    </el-dialog>

    <!-- 弹窗3 支付计划 -->
    <el-dialog :modal-append-to-body="false"
               title="支付计划"
               :visible.sync="isShowPayPlanDialog"
               width="700px"
               class="dialog-style pay-plan-dialog"
    >
      <div class="dialog-content">
        <div class="card">
          <div class="title">任务店铺</div>
          <div class="content">
            {{ salesPlanForm.shopName == "" ? "--" : salesPlanForm.shopName }}
          </div>
        </div>
        <div class="card">
          <div class="title">拍下数量</div>
          <div class="content">
            {{ salesPlanForm.taskNum == "" ? "--" : salesPlanForm.taskNum }}
          </div>
        </div>
        <div
          class="card"
          v-if="salesPlanForm.shopType == 1 || salesPlanForm.shopType == 2"
        >
          <div class="title">商品所在地</div>
          <div class="content">
            {{
              salesPlanForm.goodsAddress == ""
                ? "--"
                : salesPlanForm.goodsAddress
            }}
          </div>
        </div>
        <div class="card">
          <div class="title">计划时间</div>
          <div class="content">{{ payPlanInfo.planTime }}</div>
        </div>
        <div class="card" v-if="creatPlanType == 'sales'">
          <div class="title">本金(拍下单价*件数*单数)</div>
          <div class="content">{{ payPlanInfo.capital }}</div>
          <span
            style="color: red; margin: 0 20px"
            v-if="salesPlanForm.rebateType == 1"
          >商家返款本金</span
          >
        </div>
        <div class="card">
          <div class="title">佣金(单数*服务佣金)</div>
          <div class="content">{{ payPlanInfo.commission }}</div>
        </div>
        <div class="card">
          <div class="title">副宝贝(单数*件数*服务佣金)</div>
          <div class="content">{{ payPlanInfo.commissionShow }}</div>
        </div>
        <div class="card" v-if="isShowOtherService">
          <div class="title">其他服务</div>
          <div class="content">
            <div
              v-for="(item, index) in payPlanInfo.otherService"
              :key="index"
              v-if="item.isShow"
            >
              {{ item.name }}：{{ item.price }}
            </div>
          </div>
        </div>
        <div class="card">
          <div class="title">本次合计冻结金额</div>
          <div class="content">{{ payPlanInfo.freezeMoney }}</div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancel-btn" @click="showPayPlanDialog"
        >返回修改</el-button
        >
        <el-button
          class="submit-btn"
          :disabled="submitLoading"
          :loading="submitLoading"
          @click="payPlan"
        >确认</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  apiShopTagInfo,
  apiGetGoodsInfo,
  apiMerchantGoods,
  apiGetRemarkList,
  apiGetServiceFeeList,
  apiMerchantUserStatus,
  apiCreateTiktokDragPlan,
  apiSaleDetail,
  apiFlowDetail,
  apiIsBindShop,
  apiTiktokDragSaleDetail,
} from "../../request/api.js";
import { mapGetters, mapActions } from "vuex";
import moment from "moment";

export default {
  data() {
    return {
      hideOrShow: false,
      noticeList: [],
      activeNoticeIndex: 0,
      noticeShow: true,
      // activeName: 'tab1',
      creatPlanType: "sales", //计划类型
      isForbidModify: false, //重新支付禁止修改
      isForbidRevise: false, //抓取商品信息成功后禁止修改信息
      trafficOrderNum: 0,

      // 商品信息设置数据
      salesPlanForm: {
        token: "",
        shopId: "",
        shopName: "", // 店铺名称
        productId: "",
        planName: "", // 计划名称
        payMoney: "",
        goodsUrl: "",
        goodsTitle: "",
        shopType: "", // 店铺种类
        goodsSeller: "",
        showMoney: "",
        payPerson: "",
        goodsAddress: "",
        goodsImg: "",
        taskNum: "1", // 销量任务
        goodsNum: "", // 商品数量
        entranceType: 1, // 入口类型
        planMessage: [
          // 存储商品信息循环模块
          {
            goodsUrl: "", // 商品链接
            productId: "", // 商品id
            goodsTitle: "", // 商品标题
            shopName: "", // 店铺名称
            shopId: "", // 店铺id
            buyNum: 1, // 每单拍n件
            sku: "", // 拍下规格
            payMoney: 0, // 拍下单价
            goodsSeller: "", // 掌柜昵称
            showMoney: "0", // 搜索展示价格
            payPerson: "1", // 付款人数约
            goodsAddress: "1", // 商品归属地
            goodsImg: "", // 商品主图
            shopType: "", // 店铺类型
          },
        ],
        allotType: 1,
        planOver: 2,
        startTime: "",
        endTime: "",
        overTime: "",
        planTime: "",
        remark: "",
        placementArea: "",
        ageId: "99",
        sexId: "99",
        creditId: "99",
        modelId: "99",
        checkContent: "",
        rebateType: "",
        tk: 2,
        zqdType: "0",
        zqd: 2,
        payType: "",
        keyword: "", // 二维码、关键字
      },

      // 当前点击选择商品对应的下标
      currentIndex: "",

      // 商品信息设置表单验证
      goodsRules: {
        goodsUrl: [{ required: true, message: "不能为空", trigger: "blur" }],
        productId: [{ required: true, message: "不能为空", trigger: "blur" }],
        goodsTitle: [{ required: true, message: "不能为空", trigger: "blur" }],
        shopName: [{ required: true, message: "不能为空", trigger: "blur" }],
        buyNum: [{ required: true, message: "不能为空", trigger: "blur" }],
        sku: [{ required: true, message: "不能为空", trigger: "blur" }],
        payMoney: [{ required: true, message: "不能为空", trigger: "blur" }],
        showMoney: [{ required: true, message: "不能为空", trigger: "blur" }],
        payPerson: [{ required: true, message: "不能为空", trigger: "blur" }],
        goodsAddress: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
      },
      // 计划信息设置表单验证
      planInformationRules: {
        planName: [
          { required: true, message: "请输入计划名称", trigger: "blur" },
        ],
        shopId: [
          { required: true, message: "请输入店铺名称", trigger: "blur" },
        ],
        shopType: [
          { required: true, message: "请输入店铺类型", trigger: "blur" },
        ],
        entranceType: [
          { required: true, message: "选择入口类型", trigger: "blur" },
        ],
        keyword: [{ required: true, message: "不能为空", trigger: "blur" }],
        taskNum: [
          { required: true, message: "请输入销量任务", trigger: "blur" },
        ],
      },

      // 改造后的店铺数据
      initShopNameList: [],

      // 店铺名称列表
      shopNameList: [],
      platformNameObject: {
        1: "淘宝",
        2: "天猫",
        3: "京东",
        4: "1688",
        13: "唯品会",
        15: "拼多多",
        20: "抖音",
      },
      tagsList: {},
      shopShowType: "",
      // 店铺类型
      platformTypeList: [{
        label: "抖音",
        value: 20,
      }],
      initPlatformTypeList: [
        {
          label: "淘宝",
          value: 1,
        },
        {
          label: "天猫",
          value: 2,
        },
        {
          label: "京东",
          value: 3,
        },
        {
          label: "1688",
          value: 4,
        },
        {
          label: "唯品会",
          value: 13,
        },
        {
          label: "拼多多",
          value: 15,
        },
        {
          label: "抖音",
          value: 20,
        },
      ],
      uploadData: {
        area: "goods",
      },
      uploadQrcodeData: {
        area: "qrCode",
      },
      isWphUrl: false,
      isShowGoodsDialog: false,
      // 商品选择
      goodsSelect: {
        token: "",
        page: 1,
        pageSize: 100,
        shopId: "",
        shopType: "",
        productId: "",
      },
      goodsList: [],
      curSelectGoodsIndex: "",
      curSelectGoods: {},
      entranceTypeList: [
        {
          label: "关键词",
          value: 1,
        },
        {
          label: "抖口令",
          value: 2,
        },
        {
          label: "二维码",
          value: 3,
        },
        {
          label: "直播",
          value: 4,
        },
      ],
      entranceTypeName: {
        1: "关键词",
        2: "抖口令",
        3: "二维码",
        4: "视频链接",
        5: "店铺名",
      },
      curQrcodeIndex: 0,
      taskTypeList: [
        {
          list: [
            {
              type: 1,
              name: "浏览",
            },
            {
              type: 2,
              name: "浏览+关注",
            },
            {
              type: 3,
              name: "浏览+加购",
            },
            {
              type: 4,
              name: "浏览+收藏",
            },
          ],
        },
        {
          list: [
            {
              type: 5,
              name: "浏览+加购+关注",
            },
            {
              type: 6,
              name: "浏览+关注+收藏",
            },
            {
              type: 7,
              name: "浏览+加购+收藏",
            },
            {
              type: 8,
              name: "浏览+加购+关注+收藏",
            },
          ],
        },
      ],
      tabsList: [
        {
          type: 1,
          name: "平均分配",
        },
        {
          type: 2,
          name: "手动分配",
        },
        {
          type: 3,
          name: "指定时间",
        },
      ],
      setPlanTime: {
        startTime: "",
        endTime: "",
        overTime: "",
      },
      pickerOptions1: {
        disabledDate(time) {
          let curDate = new Date().getTime();
          let three = 6 * 24 * 3600 * 1000;
          let threeMonths = curDate + three;
          return (
            time.getTime() < Date.now() - 8.64e7 || time.getTime() > threeMonths
          );
        },
      },
      pickerOptions2: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      totalAllotNum: 0,
      isForbidEditNum: false,
      intendOrderNum: 0,
      oldOverTime: "",
      remarkList: [],
      showSexArr: [1, 2, 13],
      showCreditArr: [1, 2],
      showCheckContentArr: [1, 2],
      showZqdArr: [1, 2],
      isShowAreaDialog: false,
      tagsDefaultPrice: [],
      // 计算佣金
      serviceFeeList: [],
      ageIdArr: ["99"],
      checkContent: "",
      checkContentStatus: false,
      tkCheckType: 2,
      zqdTypeData: [
        {
          value: "0",
          label: "全部",
        },
        {
          value: "1",
          label: "一天内浏览过",
        },
        {
          value: "2",
          label: "两天内浏览过",
        },
        {
          value: "3",
          label: "三天内浏览过",
        },
        {
          value: "4",
          label: "一周内浏览过",
        },
      ],
      isIndeterminate: false,
      provinceOpitons: [
        {
          area: "华东地区",
          province: ["北京市", "天津市", "河北省", "山西省", "内蒙古自治区"],
          checkedCities: [
            "北京市",
            "天津市",
            "河北省",
            "山西省",
            "内蒙古自治区",
          ],
          isIndeterminate: false,
          checkAll: true,
        },
        {
          area: "东北地区",
          province: ["辽宁省", "吉林省", "黑龙江省"],
          checkedCities: ["辽宁省", "吉林省", "黑龙江省"],
          isIndeterminate: false,
          checkAll: true,
        },
        {
          area: "华东地区",
          province: [
            "上海市",
            "江苏省",
            "浙江省",
            "安徽省",
            "福建省",
            "山东省",
          ],
          checkedCities: [
            "上海市",
            "江苏省",
            "浙江省",
            "安徽省",
            "福建省",
            "山东省",
          ],
          isIndeterminate: false,
          checkAll: true,
        },
        {
          area: "华中地区",
          province: ["江西省", "河南省", "湖北省", "湖南省"],
          checkedCities: ["江西省", "河南省", "湖北省", "湖南省"],
          isIndeterminate: false,
          checkAll: true,
        },
        {
          area: "华南地区",
          province: ["广东省", "广西壮族自治区", "海南省"],
          checkedCities: ["广东省", "广西壮族自治区", "海南省"],
          isIndeterminate: false,
          checkAll: true,
        },
        {
          area: "西南地区",
          province: ["重庆市", "四川省", "贵州省", "云南省", "西藏自治区"],
          checkedCities: ["重庆市", "四川省", "贵州省", "云南省", "西藏自治区"],
          isIndeterminate: false,
          checkAll: true,
        },
        {
          area: "西北地区",
          province: [
            "陕西省",
            "甘肃省",
            "青海省",
            "宁夏回族自治区",
            "新疆维吾尔族自治区",
          ],
          checkedCities: [
            "陕西省",
            "甘肃省",
            "青海省",
            "宁夏回族自治区",
            "新疆维吾尔族自治区",
          ],
          isIndeterminate: false,
          checkAll: true,
        },
        // ,{
        //   area: '其他地区',
        //   province: [
        //     '香港特别行政区',
        //     '澳门特别行政区',
        //     '台湾省'
        //   ],
        //   checkedCities: [],
        //   isIndeterminate: false,
        //   checkAll: false
        // },
      ],
      checkAll: false,
      isShowPayPlanDialog: false,
      submitLoading: false,
      // 支付计划信息
      payPlanInfo: {
        planTime: "",
        // 本金字符串显示
        capital: "",
        // 佣金
        commission: "",
        // 副宝贝字符串显示
        commissionShow: "",
        // 副宝贝佣金
        copyCommission: "",
        otherService: {
          sex: {},
          age: {},
          model: {},
          credit: {},
          zqd: {},
        },
        // 支付合计金额
        freezeMoney: 0,
      },
      index: 0, // 就一个下标
      indexOne: 1, // 就一个下标
      goodsMaxNum: 5, // 商品最大数量
      // 店铺列表
      originalShopNameList: [],
      isUploadGoodsImg: false,
      isShowOtherService: false,
      planType: this.$route.query.type,
      planId: this.$route.query.id,
      userToken: window.localStorage.getItem("token"),
      merchantData: JSON.parse(window.localStorage.getItem("merchantConfig")),
      isShowAddButton: true, // 是否能用添加按钮
    };
  },

  // 生命周期钩子函数
  created() {
    // 调用公告弹窗
    this.setNoticeList();
    // 调用绑定店铺
    this.bindShop();
    // if (this.creatPlanType == "sales") {
    //   if (
    //     !this.merchantData.shop_show_type ||
    //     this.merchantData.shop_show_type == null
    //   ) {
    //     // 店铺种类
    //     this.platformTypeList = this.initPlatformTypeList;
    //   } else {
    //     let shopShowTypeArr = this.merchantData.shop_show_type.split(",");
    //     // console.log(this.merchantData);
    //     for (var i in this.initPlatformTypeList) {
    //       if (
    //         shopShowTypeArr.indexOf(
    //           this.initPlatformTypeList[i].value.toString()
    //         ) >= 0
    //       ) {
    //         this.platformTypeList.push(this.initPlatformTypeList[i]);
    //       }
    //     }
    //   }
    // }

    // 获取店铺tap信息
    this.getShopTagInfo();
    this.goodsSelect.token = this.userToken;
    // 搜索商品数据
    this.searchGoodsData();
    // 发布时间设置
    this.initCurTime();
    this.getRemarkList();

    this.getServiceFeeList();
    if (this.creatPlanType == "sales") {
      this.getMerchantUserStatus();
    }
    this.salesPlanForm.token = this.userToken;
    if (this.planId) {
      // 页面加载调用 获取计划详情
      this.getPlanDetail();
    }
  },

  // 侦听器
  watch: {
    //监听路由跳转
    $route: {
      handler: function (to, from) {
        // 判断跳转的页面
        if (to.path == "/plan/createTiktokDragPlan") {
          // 赋值创建计划类型
          this.creatPlanType = "sales";
          // 改造数据
          this.entranceTypeName = {
            1: "关键词",
            2: "抖口令",
            3: "二维码",
            4: "视频链接",
            5: "店铺名",
          };
          // this.planForm = this.salesPlanForm;
          // 用 salesPlanForm
        }
      },
      immediate: true,
    },

    "setPlanTime.endTime": function (val) {
      if (this.salesPlanForm.allotType == 2 && !val) {
        this.setPlanTime.endTime = moment()
          .set("hour", 23)
          .set("minute", 59)
          .toDate()
          .getTime();
        this.changeManualAllocationOverTime();
      }
    },

    "setPlanTime.startTime": function (val) {
      if (this.salesPlanForm.allotType == 2 && !val) {
        this.setPlanTime.startTime = moment()
          .set("hour", 0)
          .set("minute", 0)
          .toDate()
          .getTime();
      }
    },
  },

  // 自定义处理函数
  methods: {
    //===============公共================

    // 设置公告弹窗
    setNoticeList() {
      if (this.merchantData) {
        this.noticeList = this.merchantData.message_list;
      }
    },

    // 绑定店铺
    bindShop() {
      // 发送请求
      apiIsBindShop({
        token: this.userToken,
      })
        .then((res) => {
          if (res.code == -1) {
            this.$message.error("你尚未绑定店铺，请先前往绑定");
            setTimeout(() => {
              this.$router.push("/shopManage/shopManage");
            }, 1000);
          }
        })
        .catch((res) => {
          this.$message.error(res.msg);
        });
    },

    // 获取商户身份
    getMerchantUserStatus() {
      // 发请求
      apiMerchantUserStatus({
        token: this.userToken,
      })
        .then((res) => {
          if (res.code == 1) {
            this.checkContentStatus =
              res.msg.check_content_status == 2 ? true : false;
            this.salesPlanForm.rebateType = res.msg.rebate_type;
            this.tkCheckType = res.msg.tk_check_type;
          }
          // console.log(this.checkContentStatus);
        })
        .catch((res) => {});
    },

    getServiceFeeList() {
      // 获取佣金
      apiGetServiceFeeList({
        token: this.userToken,
      })
        .then((res) => {
          if (res.code == 1) {
            this.serviceFeeList = res.msg;
            // console.log(this.serviceFeeList);
            // 赋值副宝贝金额
            this.payPlanInfo.copyCommission = this.serviceFeeList.attachprice;
            // 调用平台形式类型改变
            this.platFormTypeChange();
          }
        })
        .catch((res) => {});
    },

    getRemarkList() {
      apiGetRemarkList()
        .then((res) => {
          if (res.code == 1) {
            this.remarkList = res.msg;
          }
        })
        .catch((res) => {});
    },

    // 获取店铺tap信息
    getShopTagInfo() {
      // 发请求
      apiShopTagInfo({
        token: this.userToken,
        shop_type: 20
      })
        .then((res) => {
          // console.log(res);
          if (res.code == 1) {
            //店铺列表
            this.originalShopNameList = res.msg.shop_list;
            for (var i in res.msg.shop_list) {
              this.initShopNameList.push({
                name:
                  this.platformNameObject[res.msg.shop_list[i].type] +
                  "-" +
                  res.msg.shop_list[i].name,
                type: res.msg.shop_list[i].type,
                id: res.msg.shop_list[i].id,
                bind_status: res.msg.shop_list[i].bind_status
              });
            }
            // 数据改造后的店铺列表
            this.shopNameList = this.initShopNameList;
            //接单参数
            var arr = res.msg.tag_list;
            var tagNameArr = [
              "age_list",
              "sex_list",
              "model_list",
              "credit_list",
              "address_list",
            ];
            for (var i in arr) {
              for (var j in tagNameArr) {
                if (i == j) {
                  this.$set(this.tagsList, tagNameArr[j], arr[i]);
                }
              }
            }
          }
        })
        .catch((res) => {});
    },

    //   自定义搜索方法
    dataFilter(val) {
      this.salesPlanForm.shopName = val;
      if (val) {
        this.shopNameList = this.initShopNameList.filter((item) => {
          if (
            !!~item.name.indexOf(val) ||
            !!~item.name.toUpperCase().indexOf(val.toUpperCase())
          ) {
            return true;
          }
        });
      } else {
        this.shopNameList = this.initShopNameList;
      }
    },
    changeShop(val) {
      if (this.merchantData.douyin_force_auth == 1){
        this.hideOrShow = true;
        for (const shop of this.shopNameList) {
          if (shop.id == val){
            if (shop.bind_status == 2){
              this.hideOrShow = false;
              return this.$message.error("店铺未授权");
            }
          }
        }
      }
    },
    /*// 是否隐藏淘客选项
    isHideTaoKeCard() {
      this.salesPlanForm.planMessage.forEach((item, index) => {
        if (
          this.salesPlanForm.planMessage[index].goodsUrl.indexOf("item.jd.com") != -1 ||
          this.salesPlanForm.planMessage[index].goodsUrl.indexOf("item.m.jd.com") != -1 ||
          this.salesPlanForm.planMessage[index].goodsUrl.indexOf("yangkeduo.com") != -1 ||
          this.salesPlanForm.planMessage[index].goodsUrl.indexOf("detail.1688.com") != -1 ||
          this.salesPlanForm.planMessage[index].goodsUrl.indexOf("pinduoduo.com") != -1 ||
          this.salesPlanForm.planMessage[index].goodsUrl.indexOf("haohuo.jinritemai.com") != -1
        ) {
          // 隐藏淘客选项
          this.tkCheckType = 2
        } else {
          // 展示淘客选项
          this.tkCheckType = 1
        }
      })
    },*/
    //抓取链接信息
    changeGoodsUrl(index) {
      if (
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
          "detail.tmall.com"
        ) != -1 ||
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
          "item.taobao.com"
        ) != -1 ||
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf("taobao.com") !=
        -1 ||
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf("item.jd.com") !=
        -1 ||
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
          "item.m.jd.com"
        ) != -1 ||
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
          "yangkeduo.com"
        ) != -1 ||
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
          "detail.1688.com"
        ) != -1 ||
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
          "pinduoduo.com"
        ) != -1 ||
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
          "haohuo.jinritemai.com"
        ) != -1
      ) {
        // this.isHideTaoKeCard()// 是否隐藏淘客选项
        this.isWphUrl = false;
      } else if (
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf("m.vip.com") !=
        -1 ||
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
          "detail.vip.com"
        ) != -1
      ) {
        this.isWphUrl = true;
        this.salesPlanForm.planMessage[index].productId =
          this.salesPlanForm.planMessage[index].goodsUrl
            .split("detail-")[1]
            .split(".html")[0];
      } else {
        this.isWphUrl = true;
      }
    },

    // 抓取商品
    grabGoodsInfo(index) {
      this.currentIndex = index;
      this.$loading.show("抓取中");
      if (this.salesPlanForm.planMessage[index].goodsUrl != "") {
        // let
        if (
          this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
            "detail.tmall.com"
          ) != -1 ||
          this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
            "item.taobao.com"
          ) != -1 ||
          this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
            "item.jd.com"
          ) != -1 ||
          this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
            "item.m.jd.com"
          ) != -1 ||
          this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
            "yangkeduo.com"
          ) != -1 ||
          this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
            "detail.1688.com"
          ) != -1 ||
          this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
            "pinduoduo.com"
          ) != -1 ||
          this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
            "haohuo.jinritemai.com"
          ) != -1
        ) {
          // this.isHideTaoKeCard()// 是否隐藏淘客选项
          this.isWphUrl = false;
          // 调用函数
          this.getProductId(index);
          // 发送请求
          apiGetGoodsInfo({
            goodsUrl: escape(this.salesPlanForm.planMessage[index].goodsUrl),
            token: this.userToken,
          })
            .then((res) => {
              // console.log(res);
              this.$loading.hide();
              if (res.code == 1) {
                this.isForbidRevise = true;
                this.salesPlanForm.planMessage[index].goodsTitle = res.msg.name;
                this.salesPlanForm.planMessage[index].goodsSeller =
                  res.msg.seller_name;
                this.salesPlanForm.planMessage[index].shopName =
                  res.msg.shop_name;
                // this.salesPlanForm.planMessage[index].coName = res.msg.co_name;
                this.platFormTypeChange(index);
                this.salesPlanForm.planMessage[index].shopType =
                  res.msg.shop_type;
                this.salesPlanForm.planMessage[index].goodsImg =
                  res.msg.goods_img;
                this.salesPlanForm.planMessage[index].productId =
                  res.msg.product_id;
                this.salesPlanForm.shopType = res.msg.shop_type;
                this.salesPlanForm.shopName = res.msg.shop_name;
                return this.$message.success("抓取商品信息成功");
              } else {
                // console.log(333);
                this.isForbidRevise = false;
                this.$message.error(res.msg);
              }
            })
            .catch((res) => {
              // console.log(res);
              // console.log(this.salesPlanForm.planMessage[index].goodsUrl);
              this.$loading.hide();
              this.$message.error(res.msg);
            });
        } else if (
          this.salesPlanForm.planMessage[index].goodsUrl.indexOf("m.vip.com") !=
          -1 ||
          this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
            "detail.vip.com"
          ) != -1
        ) {
          this.$loading.hide();
          this.isWphUrl = true;
          this.salesPlanForm.planMessage[index].goodsTitle = "";
          this.salesPlanForm.planMessage[index].goodsSeller = "";
          this.salesPlanForm.planMessage[index].shopName = "";
          this.salesPlanForm.planMessage[index].shopType = "";
        }
      } else {
        this.$loading.hide();
        return this.$message.error("请输入商品链接再抓取");
      }
      // console.log(this.salesPlanForm);
    },

    getProductId(index) {
      if (
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf("item.jd.com") !=
        -1 ||
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
          "item.m.jd.com"
        ) != -1
      ) {
        let urlArr =
          this.salesPlanForm.planMessage[index].goodsUrl.split(".html")[0];
        let urlArr1 = urlArr.split("/");
        this.salesPlanForm.planMessage[index].productId =
          urlArr1[urlArr1.length - 1];
      }
      if (
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
          "detail.tmall.com"
        ) != -1 ||
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
          "item.taobao.com"
        ) != -1
      ) {
        this.salesPlanForm.planMessage[index].productId = this.getRequestParam(
          this.salesPlanForm.planMessage[index].goodsUrl,
          "id"
        );
      }
      if (
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
          "yangkeduo.com"
        ) != -1
      ) {
        this.salesPlanForm.planMessage[index].productId = this.getRequestParam(
          this.salesPlanForm.planMessage[index].goodsUrl,
          "goods_id"
        );
      }
      if (
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
          "detail.1688.com"
        ) != -1
      ) {
        let urlArr =
          this.salesPlanForm.planMessage[index].goodsUrl.split(".html")[0];
        let urlArr1 = urlArr.split("/");
        this.salesPlanForm.planMessage[index].productId =
          urlArr1[urlArr1.length - 1];
      }
      if (
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
          "pinduoduo.com"
        ) != -1
      ) {
        this.salesPlanForm.planMessage[index].productId = this.getRequestParam(
          this.salesPlanForm.planMessage[index].goodsUrl,
          "gid"
        );
      }

      // 抖音;
      if (
        this.salesPlanForm.planMessage[index].goodsUrl.indexOf(
          "haohuo.jinritemai.com"
        ) != -1
      ) {
        this.salesPlanForm.planMessage[index].productId = this.getRequestParam(
          this.salesPlanForm.planMessage[index].goodsUrl,
          "id"
        );
        // console.log(this.salesPlanForm.planMessage[index].productId);
      }
    },

    getRequestParam(url, name) {
      var reg = new RegExp("(^|&|\\?)" + name + "=([^&]*)(&|$)", "i");
      var r = url.substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    },

    //选择商品按钮
    showSelectGoodsDialog(index) {
      this.currentIndex = index;
      this.curSelectGoods = {};
      this.curSelectGoodsIndex = "";
      this.goodsSelect = {
        token: this.userToken,
        page: 1,
        pageSize: 100,
        shopId: "",
        shopType: "",
        productId: "",
      };
      this.isShowGoodsDialog = true;
    },

    // 搜索商品数据
    searchGoodsData() {
      // 发送请求
      apiMerchantGoods(this.goodsSelect)
        .then((res) => {
          if (res.code == 1) {
            // 商品列表
            this.goodsList = res.msg.res;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((res) => {
          this.$message.error(res.msg);
        });
    },

    // 点击选择商品
    selectGoods(item, index) {
      this.curSelectGoods = item;
      this.curSelectGoodsIndex = index;
    },

    // 点击选择商品确认按钮
    sumbitSelectGoods(item) {
      // console.log(item);
      this.isForbidRevise = true;
      this.salesPlanForm.planMessage[this.currentIndex].goodsTitle =
        item.goods_title;
      this.salesPlanForm.planMessage[this.currentIndex].goodsSeller =
        item.selle_name;
      this.salesPlanForm.planMessage[this.currentIndex].shopName =
        item.shop_name;
      this.salesPlanForm.planMessage[this.currentIndex].shopType =
        item.shop_type;
      this.salesPlanForm.planMessage[this.currentIndex].goodsUrl =
        item.goods_url;
      this.salesPlanForm.planMessage[this.currentIndex].goodsImg =
        item.goods_img;
      this.salesPlanForm.planMessage[this.currentIndex].productId =
        item.product_id;
      this.salesPlanForm.planMessage[this.currentIndex].shopId = item.shop_id;
      this.salesPlanForm.shopName = item.shop_name;
      // 调用函数
      this.platFormTypeChange(this.currentIndex);
      this.isShowGoodsDialog = false;
      // this.isHideTaoKeCard()// 是否隐藏淘客选项
    },

    // 平台形式类型改变
    platFormTypeChange(val) {
      this.setEntranceType();
      //获取接单设置标签对应价格
      if (this.salesPlanForm.shopType == 20) {
        for (let i in this.serviceFeeList.service_fee_onedragmore) {
          if (this.serviceFeeList.service_fee_onedragmore[i].pay_type == 2) {
            this.tagsDefaultPrice.push(
              this.serviceFeeList.service_fee_onedragmore[i]
            );
          }
        }
      }
    },

    // 每个店铺类型对应入口类型
    setEntranceType() {
      if (
        this.salesPlanForm.planMessage[this.currentIndex] != 'undefined' ||
        this.salesPlanForm.planMessage[this.currentIndex].shopType == 1 ||
        this.salesPlanForm.planMessage[this.currentIndex].shopType == 2
      ) {
        if (this.creatPlanType == "sales") {
          this.entranceTypeList = [
            {
              label: "关键词",
              value: 1,
            },
            {
              label: "抖口令",
              value: 2,
            },
            {
              label: "二维码",
              value: 3,
            },
            {
              label: "直播",
              value: 4,
            },
            {
              label: "店铺名",
              value: 5,
            },
          ];
        }
      } else {
        this.entranceTypeList = [
          {
            label: "关键词",
            value: 1,
          },
          {
            label: "二维码",
            value: 3,
          },
          {
            label: "直播",
            value: 4,
          },
          {
            label: "其他",
            value: 5,
          },
        ];
      }
    },

    handleAvatarSuccess(res,file) {
      this.salesPlanForm.planMessage[res.index].goodsImg = res.msg;
      console.log(this.salesPlanForm.planMessage)
      this.isUploadGoodsImg = true;
      this.$message.success("上传成功");
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("上传商品图片大小不能超过 10MB!");
      }
      this.uploadImgStatus = 1;
      return isLt2M;
    },

    // 选择入口类型
    entranceTypeChange(val, item) {
      this.$set(item, "keyword", "");
      this.$set(item, "entranceType", val);
      this.$forceUpdate(); //强制刷新
      // console.log(val, item);
    },

    // 计划信息设置输入关键字修改格式
    expressionFilter(e) {
      // console.log(e);
      const newKeyword = e.keyword.replace(
        /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g,
        ""
      );
      this.$set(e, "keyword", newKeyword);
    },

    // 点击输入关键字...
    inputUpdate() {
      this.$forceUpdate();
    },

    // 删除商品信息模块
    cutTask(index) {
      for (var i in this.salesPlanForm.planMessage) {
        if (index == i) {
          this.salesPlanForm.planMessage.splice(i, 1);
        }
      }
      this.isShowAddButton = true;
    },

    // 添加商品信息模块
    addTask() {
      let task = {};
      task = {
        goodsUrl: "", // 商品链接
        productId: "", // 商品id
        goodsTitle: "", // 商品标题
        shopName: "", // 店铺名称
        shopId: "", // 店铺id
        buyNum: 1, // 每单拍n件
        sku: "", // 拍下规格
        payMoney: 0, // 拍下单价
        goodsSeller: "", // 掌柜昵称
        showMoney: "0", // 搜索展示价格
        payPerson: "1", // 付款人数约
        goodsAddress: "1", // 商品归属地
        goodsImg: "", // 商品主图
        shopType: "", // 店铺类型
      };
      this.salesPlanForm.planMessage.push(task);

      this.salesPlanForm.planMessage.filter((item, index) => {
        if (index > this.goodsMaxNum) {
          this.$message.success("最多只能添加6件商品");
          this.isShowAddButton = false;
          return;
        }
      });
    },

    //发布时间设置
    initCurTime() {
      var now = new Date();
      this.setPlanTime.startTime = now.getTime();
      this.setPlanTime.endTime =
        new Date(new Date().toLocaleDateString()).getTime() +
        24 * 60 * 60 * 1000 -
        1;
      if (this.salesPlanForm.allotType == 3) {
        this.setPlanTime.endTime = "";
      }
    },

    // 设置类型tap选择
    changeTimeTab(type) {
      if (this.isForbidModify) {
        return;
      }
      // 设置类型选择
      this.salesPlanForm.allotType = type;
      // 调用发布时间设置
      this.initCurTime();
      // console.log(this.salesPlanForm.allotType);
      if (this.salesPlanForm.allotType == 2) {
        // 手动分配发布时间设置
        this.selectDate();
        this.salesPlanForm.planOver = 1;
        let date = new Date(this.setPlanTime.startTime); //new Date(value*1000);根据时间戳格式进行选择乘1000或否
        let timeDate;
        let Y = date.getFullYear() + "-";
        let M =
          (date.getMonth() + 1 < 10
            ? "0" + (date.getMonth() + 1)
            : date.getMonth() + 1) + "-";
        let D =
          (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
        timeDate = Y + M + D + "23:29:59";
        this.setPlanTime.endTime = new Date(timeDate).getTime();
        let overTimeDate = Y + M + D + "23:30:00";
        this.setPlanTime.overTime = new Date(overTimeDate).getTime();
        this.oldOverTime = JSON.parse(
          JSON.stringify(this.setPlanTime.overTime)
        );
      } else {
        this.salesPlanForm.planOver = 2;
        this.setPlanTime.overTime = "";
      }
    },

    changeStartTime() {
      if (this.salesPlanForm.planOver == 1) {
        if (this.setPlanTime.overTime - this.setPlanTime.startTime < 0) {
          return this.$message.error("终止时间不能小于开始时间");
        }
      }
    },

    // 选择日期时间
    changeDate() {
      if (this.setPlanTime.startTime - this.setPlanTime.endTime > 0) {
        this.$message.error("开始时间不能大于结束时间!");
        var now = new Date();
        this.setPlanTime.startTime = now.getTime();
        this.setPlanTime.endTime =
          new Date(new Date().toLocaleDateString()).getTime() +
          24 * 60 * 60 * 1000 -
          1;
        return;
      }
      if (this.salesPlanForm.planOver == 1) {
        if (this.setPlanTime.overTime - this.setPlanTime.endTime < 0) {
          this.setPlanTime.endTime =
            new Date(new Date().toLocaleDateString()).getTime() +
            24 * 60 * 60 * 1000 -
            1;
          return this.$message.error("终止时间不能小于结束时间");
        }
      }
    },
    changeOverTime(val) {
      if (this.salesPlanForm.allotType == 2) {
        if (this.setPlanTime.overTime < this.setPlanTime.endTime) {
          this.setPlanTime.overTime = moment(this.setPlanTime.endTime)
            .toDate()
            .getTime();
          return this.$message.error("终止时间不能小于结束时间");
        }
        let newOverTime = JSON.parse(JSON.stringify(this.setPlanTime.overTime));
        newOverTime = newOverTime / 1000;
        let flag = false;
        Object.keys(this.salesPlanForm.planTime).forEach((item, index) => {
          for (var i in this.salesPlanForm.planTime[item]) {
            if (newOverTime - parseInt(i) < 0) {
              if (this.salesPlanForm.planTime[item][i] > 0) {
                this.$message.error(
                  "该终止时间后面有分配数，请先置为0在设置终止时间"
                );
                this.setPlanTime.overTime = JSON.parse(
                  JSON.stringify(this.oldOverTime)
                );
                flag = true;
                return;
              }
            }
          }
        });
        if (!flag) {
          this.oldOverTime = JSON.parse(
            JSON.stringify(this.setPlanTime.overTime)
          );
        }
      } else {
        if (this.setPlanTime.overTime - this.setPlanTime.startTime < 0) {
          this.setPlanTime.overTime = "";
          return this.$message.error("终止时间不能小于开始时间");
        }
      }
    },
    changeManualAllocationTime(val) {
      // let date = new Date(this.setPlanTime.startTime); //new Date(value*1000);根据时间戳格式进行选择乘1000或否
      // let timeDate;
      // let Y = date.getFullYear() + '-';
      // let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      // let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
      //
      // let curCheckTime = this.setPlanTime.startTime / 1000
      // let curCheckDay = this.getDateOfDay(curCheckTime);
      // let today = new Date();
      // if(curCheckDay != today.getDate()) {
      //   let startTimeDate = Y + M + D + '00:00:00';
      //   this.setPlanTime.startTime = new Date(startTimeDate).getTime()
      // }
      if (val) {
        if (
          moment(this.setPlanTime.startTime).isBefore(
            moment(this.setPlanTime.endTime)
          )
        )
          return val;
        this.$message.error("开始时间不能大于结束时间");
        this.setPlanTime.startTime = moment(this.setPlanTime.endTime).add(
          -1,
          "days"
        );
      } else {
        // this.setPlanTime.startTime = moment().set('hour', 0).set('minute', 0).toDate().getTime()
      }

      // timeDate = Y + M + D + '23:29:59';
      // this.setPlanTime.endTime = new Date(timeDate).getTime()
      // let overTimeDate = Y + M + D + '23:30:00';
      // this.setPlanTime.overTime = new Date(overTimeDate).getTime()
      // this.oldOverTime = JSON.parse(JSON.stringify(this.setPlanTime.overTime))
    },
    changeManualAllocationEndTime(val) {
      if (val) {
        this.changeManualAllocationOverTime();
        if (moment(this.setPlanTime.startTime).isBefore(moment(val)))
          return val;
        this.setPlanTime.endTime = moment(this.setPlanTime.startTime).add(
          1,
          "days"
        );
        this.changeManualAllocationOverTime();
        this.$message.error("开始时间不能大于结束时间");
      } else {
        // this.setPlanTime.endTime = moment().set('hour', 23).set('minute', 59).toDate().getTime()
        // this.changeManualAllocationOverTime()
        // console.log(this.setPlanTime.endTime)
        // this.setPlanTime.endTime = new Date().getTime()
      }
    },

    changeManualAllocationOverTime() {
      this.setPlanTime.overTime = moment(this.setPlanTime.endTime)
        .toDate()
        .getTime();
      this.oldOverTime = JSON.parse(JSON.stringify(this.setPlanTime.overTime));
    },

    // 手动分配发布时间设置
    selectDate() {
      this.$forceUpdate();
      if (this.setPlanTime.startTime == "" && this.setPlanTime.endTime == "") {
        return;
      }
      // =============
      var startTimestamp = this.setPlanTime.startTime / 1000;
      var endTimestamp = this.setPlanTime.endTime / 1000;
      //获取哪天
      var startTimeOfDay = this.getDateOfDay(startTimestamp);
      var endTimeOfDay = this.getDateOfDay(endTimestamp);
      //获取开始时间在哪个小时
      var startTimeOfHours = this.getDateOfHours(startTimestamp);
      var endTimeOfHours = this.getDateOfHours(endTimestamp);
      //获取第几年
      var startTimeOYear = this.getDateOfYear(startTimestamp);
      var endTimeOYear = this.getDateOfYear(endTimestamp);
      //获取第几月
      var startTimeOfMonth = this.getDateOfMonth(startTimestamp);
      var endTimeOfMonth = this.getDateOfMonth(endTimestamp);
      //开始时间当天的小时差
      var curPeriod = 24 - startTimeOfHours;
      var timeJosn = {};
      var curTimeKey =
        startTimeOYear +
        "-" +
        startTimeOfMonth +
        "-" +
        startTimeOfDay +
        " " +
        startTimeOfHours +
        ":" +
        "00:00";

      var newCurTimeKey = this.dateToUnix(curTimeKey);

      //开始时间到结束时间相差几天
      var dayNum = endTimeOfDay - startTimeOfDay;
      //当dayNum=0时，开始时间跟结束时间在同一天

      //判断开始时间和结束时间是否在同一个月
      if (startTimeOfMonth == endTimeOfMonth) {
        //判断开始时间和结束时间是否在同一天
        if (dayNum == 0) {
          timeJosn[newCurTimeKey] = {};
          var now = new Date();
          var hour = now.getHours();
          let newPeriod = 24 - hour;
          if (startTimeOfDay != now.getDate()) {
            for (var i = 0; i < curPeriod; i++) {
              var date =
                startTimeOYear +
                "-" +
                startTimeOfMonth +
                "-" +
                startTimeOfDay +
                " " +
                (parseInt(startTimeOfHours) + i) +
                ":" +
                "00:00";
              timeJosn[newCurTimeKey][this.dateToUnix(date)] = 0;
            }
          } else {
            for (var i = 1; i < newPeriod; i++) {
              var date =
                startTimeOYear +
                "-" +
                startTimeOfMonth +
                "-" +
                startTimeOfDay +
                " " +
                (parseInt(hour) + i) +
                ":" +
                "00:00";
              timeJosn[newCurTimeKey][this.dateToUnix(date)] = 0;
            }
          }
        } else {
          //当开始时间跟结束时间相差一天以上，就要把当天跟后面几天合在一起
          timeJosn[newCurTimeKey] = {};
          for (var i = 1; i < curPeriod; i++) {
            var date =
              startTimeOYear +
              "-" +
              startTimeOfMonth +
              "-" +
              startTimeOfDay +
              " " +
              (parseInt(startTimeOfHours) + i) +
              ":" +
              "00:00";
            timeJosn[newCurTimeKey][this.dateToUnix(date)] = 0;
          }
          //第二天开始
          for (var i = 0; i < dayNum; i++) {
            var timeKey =
              startTimeOYear +
              "-" +
              startTimeOfMonth +
              "-" +
              (parseInt(startTimeOfDay) + (i + 1)) +
              " " +
              startTimeOfHours +
              ":" +
              "00:00";
            var newTimeKey = this.dateToUnix(timeKey);
            timeJosn[newTimeKey] = {};
            for (var j = 0; j < 24; j++) {
              var date =
                startTimeOYear +
                "-" +
                startTimeOfMonth +
                "-" +
                (parseInt(startTimeOfDay) + (i + 1)) +
                " " +
                j +
                ":" +
                "00:00";
              timeJosn[newTimeKey][this.dateToUnix(date)] = 0;
            }
          }
        }
      } else {
        //开始时间那个月的总天数
        var startTimeOfMonthAllDay = this.getMonDay(this.setPlanTime.startTime);
        //结束时间那个月的第几天
        var endtDateOfNowDay = this.getNowDay(this.setPlanTime.endTime);

        timeJosn[newCurTimeKey] = {};
        for (var i = 1; i < curPeriod; i++) {
          var date =
            startTimeOYear +
            "-" +
            startTimeOfMonth +
            "-" +
            startTimeOfDay +
            " " +
            (parseInt(startTimeOfHours) + i) +
            ":" +
            "00:00";
          timeJosn[newCurTimeKey][this.dateToUnix(date)] = 0;
        }
        var curDayNum = startTimeOfMonthAllDay - startTimeOfDay;
        for (var i = 0; i < curDayNum; i++) {
          var timeKey =
            startTimeOYear +
            "-" +
            startTimeOfMonth +
            "-" +
            (parseInt(startTimeOfDay) + (i + 1)) +
            " " +
            startTimeOfHours +
            ":" +
            "00:00";
          var newTimeKey = this.dateToUnix(timeKey);
          timeJosn[newTimeKey] = {};
          for (var j = 0; j < 24; j++) {
            var date =
              startTimeOYear +
              "-" +
              startTimeOfMonth +
              "-" +
              (parseInt(startTimeOfDay) + (i + 1)) +
              " " +
              j +
              ":" +
              "00:00";
            timeJosn[newTimeKey][this.dateToUnix(date)] = 0;
          }
        }
        //获取下个月的
        for (var i = 0; i < endtDateOfNowDay; i++) {
          var timeKey =
            endTimeOYear +
            "-" +
            endTimeOfMonth +
            "-" +
            (i + 1) +
            " " +
            endTimeOfHours +
            ":" +
            "00:00";
          var newTimeKey = this.dateToUnix(timeKey);
          timeJosn[newTimeKey] = {};
          for (var j = 0; j < 24; j++) {
            var date =
              endTimeOYear +
              "-" +
              endTimeOfMonth +
              "-" +
              (i + 1) +
              " " +
              j +
              ":" +
              "00:00";
            timeJosn[newTimeKey][this.dateToUnix(date)] = 0;
          }
        }
      }

      this.salesPlanForm.planTime = timeJosn;

      this.totalAllocation();
    },

    // 已分配总计
    totalAllocation() {
      let totalNumber = 0;
      Object.keys(this.salesPlanForm.planTime).forEach((item) => {
        Object.keys(this.salesPlanForm.planTime[item]).forEach((ite) => {
          totalNumber += this.salesPlanForm.planTime[item][ite];
        });
      });
      this.totalAllotNum = totalNumber;
    },

    // 计划中单数
    countIntendOrderNum() {
      var ordNumber = 0;
      // let number = 0;
      // this.salesPlanForm.planMessage.forEach((item, index) => {
      ordNumber += parseInt(this.salesPlanForm.taskNum);
      // for (const i in item.taskType) {
      //   number += parseInt(item.taskType[i]);
      // }
      // });

      this.intendOrderNum = ordNumber;
      // this.trafficOrderNum = number;
      if (this.creatPlanType === "sales") {
        return ordNumber;
      }
      // else {
      //   return number;
      // }
    },

    // 数量里面的时间选择
    changeAllotNum(timeItem, itemKey) {
      this.totalAllocation();
      if (this.creatPlanType === "sales") {
        if (this.totalAllotNum > this.intendOrderNum) {
          this.isForbidEditNum = true;
          this.$nextTick(() => {
            this.$set(timeItem, itemKey, 0);
            this.totalAllocation();
          });
          this.$message.error("分配数不能超过计划中的单数!");
        } else {
          this.isForbidEditNum = false;
        }
      } else {
        if (this.totalAllotNum > this.trafficOrderNum) {
          this.isForbidEditNum = true;
          this.$nextTick(() => {
            this.$set(timeItem, itemKey, 0);
            this.totalAllocation();
          });
          this.$message.error("分配数不能超过计划中的单数!");
        } else {
          this.isForbidEditNum = false;
        }
      }

      let newOverTime = JSON.parse(JSON.stringify(this.setPlanTime.overTime));
      newOverTime = newOverTime / 1000;
      if (newOverTime - parseInt(itemKey) < 0) {
        this.isForbidEditNum = true;
        this.$nextTick(() => {
          this.$set(timeItem, itemKey, 0);
          this.totalAllocation();
        });
        this.$message.error("不能在终止时间后进行分配");
      }
      setTimeout(() => {
        this.isForbidEditNum = false;
      }, 5000);
    },

    // 商家要求
    clickRemarkText(content) {
      if (this.salesPlanForm.remark.length >= 150) {
        return;
      }
      this.salesPlanForm.remark += content + ";";
    },

    // 处理时间格式
    dateToUnix(string) {
      var f = string.split(" ", 2);
      var d = (f[0] ? f[0] : "").split("-", 3);
      var t = (f[1] ? f[1] : "").split(":", 3);
      return (
        new Date(
          parseInt(d[0], 10) || null,
          (parseInt(d[1], 10) || 1) - 1,
          parseInt(d[2], 10) || null,
          parseInt(t[0], 10) || null,
          parseInt(t[1], 10) || null,
          parseInt(t[2], 10) || null
        ).getTime() / 1000
      );
    },

    getNowDay(mydate) {
      var d = new Date(mydate);
      return d.getDate();
    },
    //获取当月总共几天
    getMonDay(mydate) {
      var d = new Date(mydate);
      //d.getMonth()+1月份索引从0开始,天数索引从1开始，第0天即代表最后一天
      var allDays = new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();
      return allDays;
    },

    //获取开始时间在哪个小时
    getDateOfHours(val) {
      var date = new Date(val * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var h = date.getHours();
      return h;
    },

    //获取第几月
    getDateOfMonth(val) {
      var date = new Date(val * 1000);
      var m =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      return m;
    },

    //获取哪天
    getDateOfDay(val) {
      var date = new Date(val * 1000);
      var d = date.getDate();
      return d;
    },

    // 获取第几年
    getDateOfYear(val) {
      var date = new Date(val * 1000);
      var y = date.getFullYear();
      return y;
    },
    formatDate(now) {
      let year = now.getFullYear();
      let month = now.getMonth() + 1;
      let date = now.getDate();
      let hour = now.getHours();
      let minute = now.getMinutes();
      let second = now.getSeconds();
      return year + "." + month + "." + date;
    },

    //获取月、日
    getMonthAndDay(time) {
      var date = new Date(time * 1000);
      var m =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      var d = date.getDate();
      return m + "-" + d;
    },
    //----地区---
    showAreaDialog() {
      this.isShowAreaDialog = true;
    },
    handleCheckAllChange(value, item) {
      item.checkedCities = value ? item.province : [];
      item.isIndeterminate = false;
      var flag = true;
      for (var i in this.provinceOpitons) {
        if (!this.provinceOpitons[i].checkAll) {
          flag = false;
        }
      }
      this.isIndeterminate = flag == false ? true : false;
      this.checkAll = flag == false ? false : true;
    },
    handleCheckedProvinceChange(value, item) {
      let checkedCount = value.length;
      item.checkAll = checkedCount === item.province.length;
      item.isIndeterminate =
        checkedCount > 0 && checkedCount < item.province.length;
    },
    selectAll() {
      this.checkAll != this.checkAll;
      if (this.checkAll) {
        for (var i in this.provinceOpitons) {
          this.provinceOpitons[i].checkedCities =
            this.provinceOpitons[i].province;
          this.provinceOpitons[i].isIndeterminate = false;
          this.provinceOpitons[i].checkAll = true;
        }
        this.isIndeterminate = false;
      } else {
        for (var i in this.provinceOpitons) {
          this.provinceOpitons[i].checkedCities = [];
          this.provinceOpitons[i].isIndeterminate = false;
          this.provinceOpitons[i].checkAll = false;
        }
      }
    },

    // 选择投放区域保存设置
    saveAreaData() {
      this.salesPlanForm.placementArea = "";
      var isSelectAll = false;
      for (var i in this.provinceOpitons) {
        if (!this.provinceOpitons[i].checkAll) {
          isSelectAll = true;
        }

        if (this.provinceOpitons[i].checkedCities.length > 0) {
          this.salesPlanForm.placementArea +=
            this.provinceOpitons[i].checkedCities.join(",") + ",";
        }
      }
      this.salesPlanForm.placementArea = isSelectAll
        ? this.salesPlanForm.placementArea.substring(
          0,
          this.salesPlanForm.placementArea.length - 1
        )
        : "";

      this.isShowAreaDialog = false;
    },
    //-----接单设置-----
    getTagsDefaultPrice(title) {
      for (let i in this.tagsDefaultPrice) {
        if (this.tagsDefaultPrice[i].title == title) {
          return this.tagsDefaultPrice[i].default_price;
        }
      }
    },
    changeAge(val) {
      if (val.length > 1) {
        if (val.indexOf("99") >= 0) {
          for (var i in this.ageIdArr) {
            if (this.ageIdArr[i] == "99") {
              this.ageIdArr.splice(i, 1);
            }
          }
        }
      }
      this.salesPlanForm.ageId = this.ageIdArr.join(",");
    },
    formValidate() {
      // 循环店铺列表
      for (var i in this.originalShopNameList) {
        if (this.salesPlanForm.shopId == this.originalShopNameList[i].id) {
          if (
            this.salesPlanForm.shopType != this.originalShopNameList[i].type
          ) {
            this.$message.error(
              "您选择的店铺类型与抓取的店铺类型不一致，请修改！"
            );
            return false;
          }

          // if (this.salesPlanForm.shopName.replace(/\s*/g,'') != this.originalShopNameList[i].name.replace(/\s*/g,'')) {
          //     this.$message.error('您选择的店铺与抓取的店铺不一致，请修改！')
          //     return
          // }
        }
      }

      // 循环商品信息设置
      // for (var i in this.salesPlanForm.planMessage) {
      //   if (this.salesPlanForm.entranceType == 1) {
      //     if (this.salesPlanForm.keyword == "") {
      //       this.$message.error("关键词不能为空！");
      //       return false;
      //     }
      //   }
      //   if (this.salesPlanForm.entranceType == 2) {
      //     if (this.salesPlanForm.keyword == "") {
      //       this.$message.error("淘口令不能为空！");
      //       return false;
      //     }
      //   }
      //   if (this.salesPlanForm.entranceType == 3) {
      //     if (this.salesPlanForm.keyword == "") {
      //       this.$message.error("二维码不能为空！");
      //       return false;
      //     }
      //   }
      //   if (this.creatPlanType == "sales") {
      //     if (this.salesPlanForm.planMessage[i].payMoney == "") {
      //       this.$message.error("拍下价格不能为空！");
      //       return false;
      //     }
      //   }
      // }

      if (this.salesPlanForm.allotType == 2) {
        if (this.totalAllotNum < this.intendOrderNum) {
          this.$message.error("还有未分配的单数！");
          return false;
        }
        // if (this.totalAllotNum > this.intendOrderNum) {
        //   this.$message.error('已分配总计超过计划中的单数！')
        //   return false
        // }
        if (this.creatPlanType === "sales") {
          if (this.totalAllotNum > this.intendOrderNum) {
            this.$message.error("已分配总计超过计划中的单数！");
            return false;
          }
        } else {
          if (this.totalAllotNum > this.trafficOrderNum) {
            this.$message.error("已分配总计超过计划中的单数！");
            return false;
          }
        }
      }
      if (this.isUploadGoodsImg) {
        if (this.salesPlanForm.goodsImg.indexOf("goods") < 0) {
          this.$message.error("商品主图未上传成功，请稍等或者重新上传");
          return false;
        }
      }
      if (!this.salesPlanForm.remark) {
        this.$message.error("请填写商家要求!");
        return false;
      }
      if (this.creatPlanType == "sales") {
        if (
          this.showCheckContentArr.indexOf(this.salesPlanForm.shopType) >= 0 &&
          this.checkContentStatus
        ) {
          if (
            this.salesPlanForm.checkContent.length >= 1 &&
            this.salesPlanForm.checkContent.length < 5
          ) {
            this.$message.error("商品详情页文本字数要为5个");
            return false;
          }
          if (this.salesPlanForm.checkContent.indexOf(" ") >= 0) {
            this.$message.error("商品详情页文本不能包含空格");
            return false;
          }
        }
      } else {
        var now = new Date();
        var startTimestamp = this.setPlanTime.startTime / 1000;
        var endTimestamp = this.setPlanTime.endTime / 1000;
        var startTimeOfHours = this.getDateOfHours(startTimestamp);
        var endTimeOfHours = this.getDateOfHours(endTimestamp);
        var startTimeOfDay = this.getDateOfDay(startTimestamp);
        var endTimeOfDay = this.getDateOfDay(endTimestamp);
        var dayNum = endTimeOfDay - startTimeOfDay;
        if (this.salesPlanForm.allotType == 1) {
          if (dayNum == 0) {
            if (startTimeOfHours < 6 || endTimeOfHours < 6) {
              this.$message.error("浏览单任务时间不能在00:00:00~06:00:00之间!");
              this.setPlanTime.startTime = now.getTime();
              this.setPlanTime.endTime =
                new Date(new Date().toLocaleDateString()).getTime() +
                24 * 60 * 60 * 1000 -
                1;

              return false;
            }
          } else {
            this.$message.error("浏览单任务时间不能在00:00:00~06:00:00之间!");
            this.setPlanTime.startTime = now.getTime();
            this.setPlanTime.endTime =
              new Date(new Date().toLocaleDateString()).getTime() +
              24 * 60 * 60 * 1000 -
              1;

            return false;
          }
        }
      }
      return true;
    },

    // 创建计划按钮
    creatPlanButton() {
      // 判断是否有店铺
      if (this.salesPlanForm.shopId) {
        // 遍历商品信息表单
        this.salesPlanForm.planMessage.map((value, indexs) => {
          if (this.salesPlanForm.shopName.split("").indexOf("-") != -1) {
            this.salesPlanForm.shopName =
              this.salesPlanForm.shopName.split("-");
            this.salesPlanForm.shopName =
              this.salesPlanForm.shopName[this.indexOne];
          }
          console.log(this.salesPlanForm.shopName, 1, value.shopName);
          // 计划信息设置店铺名称要和商品信息里所有商品店铺名称一致
          if (this.salesPlanForm.shopName == value.shopName) {
            console.log(this.salesPlanForm.shopName, 1, value.shopName);
            // 遍历店铺列表
            let arrshopname = this.shopNameList.filter((item) => {
              if (item.id == this.salesPlanForm.shopId) {
                return item;
              }
            });
            // 赋值给 salesPlanForm
            this.salesPlanForm.shopName = arrshopname[0].name;
            // 将字符串拆分成数组
            arrshopname = arrshopname[0].name.split("-");
            let flag = true// 控制是否有使用抓取商品信息按钮
            this.salesPlanForm.planMessage.forEach((item, index) => {
              // 没有出发抓取商品信息按钮时
              if (this.salesPlanForm.planMessage[this.currentIndex] == "undefined" || flag) {
                this.currentIndex = index
                flag = false
              }
              if (
                this.salesPlanForm.planMessage[
                  this.currentIndex
                  ].shopName.trim() != arrshopname[1].trim()
              ) {
                this.$message.error("店铺名称与商品店铺名称不一致");
                return false;
              } else {
                // 店铺名与选着的商品的店铺名称一致
                if (this.creatPlanType == "flow") {
                  var shopTypeArr = [1, 2];
                  if (shopTypeArr.indexOf(this.salesPlanForm.shopType) < 0) {
                    this.$message.error("浏览单只能发布天猫或者淘宝的商品！");
                    return;
                  }
                }

                // 通过表单验证
                this.$refs["salesPlanForm"].validate((valid) => {
                  console.log(valid); // true
                  if (valid) {
                    if (!this.formValidate()) return;

                    let discount = this.serviceFeeList["discount"];
                    let serviceFeeType = {
                      1: "service_fee_tb",
                      2: "service_fee_tm",
                      3: "service_fee_jd",
                      4: "service_fee_albb",
                      13: "service_fee_wph",
                      15: "service_fee_pdd",
                      20: "service_fee_onedragmore",
                    };

                    let serviceFee = serviceFeeType[this.salesPlanForm.shopType];
                    let curServiceFeeList = this.serviceFeeList[serviceFee];
                    let priceArr = [];

                    this.payPlanInfo.otherService = {
                      sex: {},
                      age: {},
                      model: {},
                      credit: {},
                      zqd: {},
                    };
                    this.payPlanInfo.capital = "";
                    this.payPlanInfo.commission = "";
                    this.payPlanInfo.commissionShow = "";
                    this.payPlanInfo.freezeMoney = 0;

                    // let sexPriceText = "";
                    // let agePriceText = "";
                    // let modelPriceText = "";
                    // let creditPriceText = "";
                    // let zqdPriceText = "";
                    // let tkPriceText = "";
                    //
                    // let sexPriceNum = 0;
                    // let agePriceNum = 0;
                    // let modelPriceNum = 0;
                    // let creditPriceNum = 0;
                    // let zqdPriceNum = 0;
                    // let tkPriceNum = 0;
                    //
                    // let commissionArr = [];
                    // let flowTaskTypeList = [];
                    // let flowTaskAllNum = 0;
                    // let priceFailStatus = false;

                    // 遍历商品信息设置模块
                    this.salesPlanForm.planMessage.forEach((item, index) => {
                      // console.log(item);
                      // 赋值商品数量
                      this.goodsNum = index + 1;
                      if (this.creatPlanType == "sales") {
                        // 本金字符串显示
                        this.payPlanInfo.capital +=
                          (index > 0 ? "+" : "") +
                          ("(" +
                            parseFloat(item.payMoney).toFixed(2) +
                            "*" +
                            item.buyNum +
                            "*" +
                            this.salesPlanForm.taskNum +
                            ")");

                        // 赋值给合计冻结额度
                        if (this.salesPlanForm.rebateType != 1) {
                          this.payPlanInfo.freezeMoney +=
                            parseFloat(item.payMoney) *
                            parseInt(item.buyNum) *
                            parseInt(this.salesPlanForm.taskNum);
                        }
                        this.payPlanInfo.freezeMoney = parseFloat(
                          this.payPlanInfo.freezeMoney
                        );

                      }
                      // else {
                      //   for (var i in item.taskType) {
                      //     if (this.isBlank(flowTaskTypeList[i])) {
                      //       flowTaskTypeList[i] = 0;
                      //     }
                      //     flowTaskTypeList[i] += parseInt(item.taskType[i]);
                      //   }
                      // }
                    });

                    //指定时间
                    let startTimeFormat = this.formatDate(
                      new Date(this.setPlanTime.startTime)
                    );
                    let endTimeFormat = this.setPlanTime.endTime
                      ? this.formatDate(new Date(this.setPlanTime.endTime))
                      : "";
                    let timeTypeName =
                      "(" +
                      this.tabsList[this.salesPlanForm.allotType - 1].name +
                      ")";
                    this.payPlanInfo.planTime = endTimeFormat
                      ? startTimeFormat + "--" + endTimeFormat
                      : startTimeFormat;
                    this.payPlanInfo.planTime =
                      this.payPlanInfo.planTime + timeTypeName;

                    // 本金 -- 通过初始的本金冻结金额获得
                    let capitalNum = this.payPlanInfo.freezeMoney;
                    console.log(capitalNum)
                    // 佣金对应的对象
                    let commission =
                      this.serviceFeeList.service_fee_onedragmore.filter(
                        (item) => {
                          if (
                            capitalNum / this.salesPlanForm.taskNum >= item.min &&
                            capitalNum / this.salesPlanForm.taskNum < item.max &&
                            this.salesPlanForm.shopType == item.platform_type
                          ) {
                            return item;
                          }
                        }
                      );
                    // 纯佣金 -- 未加数量
                    commission = commission[this.index].default_price;

                    // 佣金显示 * 数量
                    this.payPlanInfo.commission +=
                      "(" + this.salesPlanForm.taskNum + "*" + commission + ")";
                    // 冻结本金总额加上佣金
                    this.payPlanInfo.freezeMoney +=
                      this.salesPlanForm.taskNum * commission;

                    // 副宝贝显示
                    this.payPlanInfo.commissionShow +=
                      "(" +
                      (this.salesPlanForm.taskNum ) +
                      "*" +
                      (this.goodsNum - 1) +
                      "*" +
                      this.payPlanInfo.copyCommission +
                      ")";
                    // this.payPlanInfo.commissionShow = this.salesPlanForm.taskNum + '*' + this.payPlanInfo.commissionShow;
                    // 冻结本金总额加上副宝贝
                    this.payPlanInfo.freezeMoney +=
                      (this.salesPlanForm.taskNum ) *
                      (this.goodsNum - 1) *
                      this.payPlanInfo.copyCommission;

                    // 总金额后两位
                    this.payPlanInfo.freezeMoney =
                      this.payPlanInfo.freezeMoney.toFixed(2);
                    console.log(this.salesPlanForm)
                    this.isShowPayPlanDialog = true;
                  } else {
                    this.$message.error("创建的计划信息不完善，请先填写");
                  }
                });
              }

            })

          } else {
            // this.$message.error("店铺不一致！");
          }
        });
      } else {
        this.$message.error("请选择店铺名称");
      }
    },

    showPayPlanDialog() {
      this.isShowPayPlanDialog = false;
    },

    // 支付计划确认按钮
    payPlan() {
      if (this.payPlanInfo.freezeMoney == 0) {
        return this.$message.error("金额不能为0");
      }
      this.salesPlanForm.startTime = JSON.parse(
        JSON.stringify(Math.floor(this.setPlanTime.startTime / 1000))
      );
      this.salesPlanForm.endTime =
        this.salesPlanForm.allotType == 3
          ? ""
          : JSON.parse(
          JSON.stringify(Math.floor(this.setPlanTime.endTime / 1000))
          );
      this.salesPlanForm.overTime =
        this.salesPlanForm.planOver == 2
          ? ""
          : JSON.parse(
          JSON.stringify(Math.floor(this.setPlanTime.overTime / 1000))
          );
      if (this.salesPlanForm.placementArea) {
        this.salesPlanForm.placementArea =
          "+" + this.salesPlanForm.placementArea;
      }
      if (this.planType == "pay") {
        this.salesPlanForm.payType = "creating";
        this.salesPlanForm.id = this.planId;
      } else {
        this.salesPlanForm.payType = "";
      }
      this.submitLoading = true;
      if (this.creatPlanType == "sales") {
        // console.log(this.salesPlanForm);
        // 发送请求
        apiCreateTiktokDragPlan(this.salesPlanForm)
          .then((res) => {
            if (res.code == 1 || res.code == 1001) {
              this.submitLoading = false;
              this.isShowPayPlanDialog = false;
              let _this = this
              // return this.$message.success(res.msg);
              return this.$alert(res.msg, '提示', {
                confirmButtonText: '确定',
                callback: action => {
                  _this.$router.push("./salesPlanList");
                  // console.log(action)
                  // this.$message({
                  //   type: 'info',
                  //   message: `action: ${ action }`
                  // })
                }
              })
            } else if (res.code == 4004) {
              this.submitLoading = false;
              this.$message.error(res.msg);
              this.$router.push("../shopManage/shopManage");
            } else {
              this.submitLoading = false;
              // console.log(res);
              this.$message.error("缺少必要参数！");
            }
          })
          .catch((res) => {
            this.submitLoading = false;
            this.isShowPayPlanDialog = false;
            // console.log(res);
            this.$message.error(res.msg);
          });
      }

      // else {
      //   apiCreateFlowPlan(this.salesPlanForm)
      //     .then((res) => {
      //       if (res.code == 1 || res.code == 1001) {
      //         this.submitLoading = false;
      //         this.$router.push("./flowPlanList");
      //         this.isShowPayPlanDialog = false;
      //         return this.$message.success(res.msg);
      //       } else {
      //         this.submitLoading = false;
      //         this.$message.error(res.msg);
      //       }
      //     })
      //     .catch((res) => {
      //       this.submitLoading = false;
      //       this.isShowPayPlanDialog = false;
      //       this.$message.error(res.msg);
      //     });
      // }
    },

    // 获取计划详情
    getPlanDetail() {
      if (this.planType == "pay") {
        this.isForbidModify = true;
        this.isForbidRevise = true;
        this.isForbidEditNum = true;
      } else {
        this.isForbidRevise = true;
      }

      var areaType = 1;
      if (this.creatPlanType == "sales") {
        if (this.$route.query.shop_type != 20) {
          apiSaleDetail({
            token: this.userToken,
            id: this.planId,
          })
            .then((res) => {
              if (res.code == 1) {
                // 调用函数赋值给data
                this.analyzePlanData(res, areaType);
                // console.log(res);
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch((res) => {
              this.$message.error(res.msg);
            });
        } else {
          apiTiktokDragSaleDetail({
            token: this.userToken,
            id: this.planId,
          })
            .then((res) => {
              if (res.code == 1) {
                // 调用函数赋值给data
                this.analyzePlanData(res, areaType);
                // console.log(res);
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch((res) => {
              this.$message.error(res.msg);
            });
        }

      } else {
        apiFlowDetail({
          token: this.userToken,
          id: this.planId,
        })
          .then((res) => {
            if (res.code == 1) {
              this.analyzePlanData(res, areaType);
            } else {
              this.$message.error(res.msg);
            }
          })
          .catch((res) => {
            this.$message.error(res.msg);
          });
      }
    },

    // 页面加载调用 -- 初始化
    analyzePlanData(res, areaType) {
      if (res.msg.placement_area == "[]" || res.msg.placement_area == "") {
        this.salesPlanForm.placementArea = "";
      } else {
        var ite = unescape(res.msg.placement_area.replace(/\u/g, "%u"));
        ite = ite.replace(/\\/g, "");
        ite = ite.replace(/\"/g, "");

        if (ite.indexOf("-") >= 0) {
          ite = ite.replace(/\-/g, "");
          areaType = 2;
        } else {
          ite = ite.replace(/\+/g, "");
          areaType = 1;
        }
        var provinceArr = ite.split(",");
        for (var z in this.provinceOpitons) {
          this.provinceOpitons[z].checkedCities = [];
          this.provinceOpitons[z].isIndeterminate = false;
          this.provinceOpitons[z].checkAll = false;
        }
        for (var province in this.provinceOpitons) {
          for (var i in provinceArr) {
            for (var j in this.provinceOpitons[province].province) {
              if (
                provinceArr[i] == this.provinceOpitons[province].province[j]
              ) {
                this.provinceOpitons[province].checkedCities.push(
                  provinceArr[i]
                );
                if (
                  this.provinceOpitons[province].checkedCities.length ==
                  this.provinceOpitons[province].province.length
                ) {
                  this.provinceOpitons[province].isIndeterminate = false;
                } else {
                  this.provinceOpitons[province].isIndeterminate = true;
                }
                this.provinceOpitons[province].checkAll = true;
              }
            }
          }
          if (this.provinceOpitons[province].checkedCities.length > 0) {
            this.salesPlanForm.placementArea +=
              this.provinceOpitons[province].checkedCities.join(",") + ",";
          }
        }
        if (areaType == 2) {
          this.salesPlanForm.placementArea = "";
          for (var x in this.provinceOpitons) {
            var newArr = [];
            var checkedCitiesArr = this.provinceOpitons[x].checkedCities;
            if (checkedCitiesArr.length == 0) {
              this.provinceOpitons[x].checkedCities =
                this.provinceOpitons[x].province;
            } else {
              for (var j in this.provinceOpitons[x].province) {
                if (
                  checkedCitiesArr.indexOf(
                    this.provinceOpitons[x].province[j]
                  ) < 0
                ) {
                  newArr.push(this.provinceOpitons[x].province[j]);
                }
              }
              this.provinceOpitons[x].checkedCities = newArr;
            }
            if (
              this.provinceOpitons[x].checkedCities.length ==
              this.provinceOpitons[x].province.length
            ) {
              this.provinceOpitons[x].isIndeterminate = false;
            } else {
              this.provinceOpitons[x].isIndeterminate = true;
            }
            if (this.provinceOpitons[x].checkedCities.length == 0) {
              this.provinceOpitons[x].checkAll = false;
              this.provinceOpitons[x].isIndeterminate = false;
            } else {
              this.provinceOpitons[x].checkAll = true;
            }
            if (this.provinceOpitons[x].checkedCities.length > 0) {
              this.salesPlanForm.placementArea +=
                this.provinceOpitons[x].checkedCities.join(",") + ",";
            }
          }
        }
      }
      // this.isForbidModify = false
      this.salesPlanForm.placementArea =
        this.salesPlanForm.placementArea.substring(
          0,
          this.salesPlanForm.placementArea.length - 1
        );

      this.salesPlanForm.shopId = res.msg.merchant_shop.id; //店铺名称
      this.salesPlanForm.planName = res.msg.plan_name; //计划名称
      this.salesPlanForm.goodsImg = res.msg.goods_info.goods_img; //图片路径
      this.salesPlanForm.goodsUrl = res.msg.goods_info.goods_url; //商品url
      this.salesPlanForm.goodsTitle = res.msg.goods_info.goods_title; //商品标题
      this.salesPlanForm.shopName = res.msg.merchant_shop.name; //店铺名称
      this.salesPlanForm.goodsSeller = res.msg.merchant_shop.seller_name; //掌柜名称
      this.salesPlanForm.showMoney = res.msg.show_money; //搜索展示价格
      this.salesPlanForm.payPerson = res.msg.pay_person; //付款人数
      this.salesPlanForm.payMoney = res.msg.pay_money; //拍下单价
      this.salesPlanForm.shopType = res.msg.goods_info.shop_type; //店铺类别
      this.salesPlanForm.entranceType = res.msg.saleNum[0].entrance_type; //入口类型
      this.salesPlanForm.taskNum = res.msg.all_num;// 任务数量
      this.salesPlanForm.tk = res.msg.tk_check_type
        ? res.msg.tk_check_type.toString()
        : "2"; //淘客
      this.salesPlanForm.goodsAddress = res.msg.goods_info.goods_address;
      this.salesPlanForm.productId = res.msg.goods_info.product_id;
      this.salesPlanForm.remark = res.msg.remark;
      this.salesPlanForm.sexId =
        res.msg.sex_id == 99 ? res.msg.sex_id.toString() : res.msg.sex_id;
      this.ageIdArr = [];
      if (res.msg.age_id == 99) {
        this.ageIdArr.push("99");
      } else {
        var idArr = res.msg.age_id.toString().split(",");
        for (var idItem in idArr) {
          this.ageIdArr.push(parseInt(idArr[idItem]));
        }
      }
      this.salesPlanForm.creditId =
        res.msg.credit_id == 99
          ? res.msg.credit_id.toString()
          : res.msg.credit_id;
      this.salesPlanForm.zqd = res.msg.zqd;
      this.salesPlanForm.zqdType = !res.msg.zqd_type
        ? "0"
        : res.msg.zqd_type.toString();
      this.salesPlanForm.modelId =
        res.msg.model_id == 99 ? res.msg.model_id.toString() : res.msg.model_id;
      this.salesPlanForm.allotType = parseInt(res.msg.allot_type);
      this.salesPlanForm.checkContent = res.msg.check_content
        ? res.msg.check_content
        : "";
      this.platFormTypeChange();
      if (res.msg.over_time !== "") {
        if (res.msg.over_time == 0) {
          this.salesPlanForm.planOver = 2;
          this.setPlanTime.overTime = "";
        } else {
          this.salesPlanForm.planOver = 1;
          this.setPlanTime.overTime = "";
        }
      }
      var planfor = JSON.parse(res.msg.time_content);
      if (this.planType == "pay") {
        this.$set(
          this.salesPlanForm,
          "startTime",
          parseInt(res.msg.start_time)
        );
        this.$set(this.salesPlanForm, "endTime", parseInt(res.msg.end_time));
        this.$set(
          this.setPlanTime,
          "startTime",
          parseInt(res.msg.start_time) * 1000
        );
        this.$set(
          this.setPlanTime,
          "endTime",
          parseInt(res.msg.end_time) * 1000
        );
      }

      if (this.salesPlanForm.allotType == 2) {
        if (this.planType == "pay") {
          this.$forceUpdate(); //强制刷新
          this.salesPlanForm.planTime = planfor;
          this.totalAllocation();
        } else {
          this.changeTimeTab(this.salesPlanForm.allotType);
        }
      }
      if (this.creatPlanType == "sales") {
        // 关键字
        this.salesPlanForm.keyword = res.msg.saleNum[0].keyword
        /*res.msg.saleNum.forEach((item, index) => {
          this.salesPlanForm.planMessage[index] = {
            keyword: item.keyword,
            payMoney: item.pay_money,
            sku: item.sku,
            entranceType: item.entrance_type,
            taskNum: item.plan_num,
            buyNum: item.buy_num,
          };
        });*/
        res.msg.goodsIfo.forEach((item, index) => {
          this.salesPlanForm.planMessage[index] = {
            /*商品链接   goodsIfo -> goods_url
            商品图片链接   goodsIfo -> goods_img
            商品id      goodsIfo -> product_id
            商品标题   goodsIfo -> goods_title
            店铺名称   msg.merchant_shop.name
            每单拍      goodsIfo -> buy_num
            拍下规格   goodsIfo -> sku
            拍下单价   goodsIfo -> pay_money
            搜索展示价格   goodsIfo -> showMoney
            付款人数约      0*/
            goodsUrl: item.goods_url, // 商品链接
            productId: item.product_id, // 商品id
            goodsTitle: item.goods_title, // 商品标题
            shopName: res.msg.merchant_shop.name, // 店铺名称
            shopId: res.msg.merchant_shop.id, // 店铺id
            buyNum: item.buy_num, // 每单拍n件
            sku: item.sku, // 拍下规格
            payMoney: item.pay_money, // 拍下单价
            goodsSeller: "", // 掌柜昵称
            showMoney: item.showMoney, // 搜索展示价格
            payPerson: res.msg.pay_person, // 付款人数约
            goodsImg: item.goods_img, // 商品主图
          };
        });
      } else {
        res.msg.flowNum.forEach((item, index) => {
          this.salesPlanForm.planMessage[index] = {
            keyword: item.keyword,
            entranceType: item.entrance_type,
            taskType: {
              1: 0,
              2: 0,
              3: 0,
              4: 0,
              5: 0,
              6: 0,
              7: 0,
              8: 0,
            },
          };
          Object.keys(item.flow_task_info).forEach((ite, inde) => {
            this.salesPlanForm.planMessage[index].taskType[inde + 1] =
              item.flow_task_info[ite].num;
          });
        });
      }
    },
    isBlank(val) {
      if (val == null || val == "") {
        return true;
      }
    },
    //=========================销量=========================

    // 点击二维码上传确认按钮
    qrcodeSuccess(res, file) {
      // console.log(res,file);
      // 赋值
      this.salesPlanForm.keyword = res.msg;
      this.$forceUpdate();
      this.$message.success("上传成功");
    },

    // 最大上传大小
    qrcodeBeforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
      }
      return isLt2M;
    },

    getCheckContentText() {
      this.salesPlanForm.checkContent = this.salesPlanForm.checkContent.replace(
        /[^\a-\z\A-\Z0-9\u4E00-\u9FA5\！\!\:\;\：\；\，\,\.\。\【】\{}\ \()\-\（）]/g,
        ""
      );
      if (
        this.salesPlanForm.checkContent.length >= 1 &&
        this.salesPlanForm.checkContent.length < 5
      ) {
        this.checkContent = "";
        this.$message.error("商品详情页文本字数要为5个");
        return;
      }
      if (this.salesPlanForm.checkContent.indexOf(" ") >= 0) {
        this.checkContent = "";
        this.$message.error("商品详情页文本不能包含空格");
        return;
      }
      if (this.salesPlanForm.checkContent.length == 5) {
        var leftStr = this.salesPlanForm.checkContent.substring(0, 2);
        var rightStr = this.salesPlanForm.checkContent.substring(3, 5);
        this.checkContent = leftStr + "( )" + rightStr;
      }
    },
    //=========================流量===========================
  },
};
</script>

<style lang="less">
#create-plan {
  .plan-card {
    background: #ffffff;
    margin-bottom: 16px;
    box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
    padding-bottom: 16px;
    border-radius: 5px;
    border-top: 3px solid @themeColor;
    .plan-card-header {
      background: #ecf5ff;
      padding: 10px;
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      .title {
        line-height: 20px;
        border-left: 3px solid #666666;
        padding-left: 10px;
        font-size: 16px;
        font-weight: 700;
        color: #333333;
        width: 150px;
      }
      .tips {
        font-size: 14px;
        color: red;
      }
    }
    .plan-card-content {
      padding: 10px 20px;
      .zqd-tips {
        color: red;
        font-size: 14px;
        margin-bottom: 10px;
      }
      &.other-style {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .goods-form {
        .el-form-item {
          margin-bottom: 17px;
        }
        .form-input {
          width: 300px;
        }
        .form-btn {
          display: inline-block;
          margin-left: 20px;
          border: 1px solid @themeColor;
          border-radius: 4px;
          font-size: 12px;
          color: @themeColor;
          text-align: center;
          padding: 8px 20px;
        }
        .form-btn-tips {
          display: inline-block;
          margin-left: 20px;
          border: 1px solid #909090;
          border-radius: 4px;
          font-size: 12px;
          color: #909090;
          text-align: center;
          line-height: 28px;
          padding: 0 20px;
        }
        .other-info {
          display: flex;
          align-items: center;
          justify-content: space-between;
          .other-info-input {
            width: 100px;
          }
        }
      }
      .goods-img-box {
        margin-right: 50px;
        .goods-img {
          text-align: center;
          color: #606266;
          img {
            width: 260px;
            height: 260px;
            border: 1px dashed #666666;
          }
          .upload-icon {
            width: 260px;
            height: 260px;
            border: 1px dashed #666666;
            text-align: center;
            line-height: 260px;
            color: #a5a5a5;
            font-size: 30px;
          }
        }
      }
      // 计划信息设置表单样式
      .planInformation-card {
        height: 100%;
        width: 100%;
        margin: 0 0 0 50px;
        .planInfo-input {
          width: 300px;
        }
        .avatar {
          width: 200px;
          height: 200px;
          border: 1px dashed #666666;
        }
        .upload-icon {
          width: 200px;
          height: 200px;
          border: 1px dashed #a5a5a5;
          text-align: center;
          line-height: 200px;
          color: #a5a5a5;
          font-size: 20px;
        }
      }
      // 任务信息样式
      .task-card {
        display: flex;
        align-items: center;
        justify-content: space-between;
        border: 1px dashed #a5a5a5;
        padding: 36px 20px 20px 20px;
        .task-card-left {
          .form-box {
            margin-bottom: 16px;
            .title {
              font-size: 14px;
              color: @fontSubtitleColor;
              width: 80px;
              text-align: right;
              display: inline-block;
              .star-text {
                color: red;
              }
            }
            .form-input {
              width: 200px;
              vertical-align: middle;
              margin-left: 5px;
            }
            img {
              width: 200px;
              height: 200px;
              border: 1px dashed #a5a5a5;
              vertical-align: text-top;
            }
            .qrcode-img-box {
              display: inline-block;
              margin-left: 5px;
              img {
                width: 200px;
                height: 200px;
                border: 1px dashed #a5a5a5;
              }
            }
          }
        }
        .task-card-center {
          &.flow-center {
            display: flex;
            align-items: center;
          }
          .center-cell {
            display: flex;
            align-items: center;
          }
          .form-box {
            margin-bottom: 16px;
            margin-right: 20px;
            color: @fontSubtitleColor;
            font-size: 14px;
            .title {
              font-size: 14px;
              color: @fontSubtitleColor;
              width: 80px;
              text-align: right;
              display: inline-block;
              .star-text {
                color: red;
              }
            }
            .form-input {
              width: 150px;
              vertical-align: middle;
              margin: 0 5px;
            }
          }
          .center-row {
            .flow-form-box {
              margin-bottom: 16px;
              margin-right: 20px;
              color: @fontSubtitleColor;
              font-size: 14px;
              .title {
                font-size: 14px;
                color: @fontSubtitleColor;
                width: 160px;
                text-align: right;
                display: inline-block;
              }
              .form-input {
                width: 100px;
                vertical-align: middle;
                margin: 0 5px;
              }
            }
          }
        }
        .task-card-right {
          i {
            font-size: 20px;
            padding: 8px;
            cursor: pointer;
            display: block;
          }
          .add-task-icon {
            color: @themeColor;
          }
          .cut-task-icon {
            color: red;
          }
        }
      }
      .time-type-box {
        display: flex;
        align-items: center;
        .title {
          font-size: 14px;
          color: @fontSubtitleColor;
          width: 80px;
          text-align: right;
          display: inline-block;
        }
        .tabs-nav {
          border-radius: 5px;
          border: 1px solid #e0e0e0;
          &.disabled-click {
            background: #f5f7fa;
            .tab {
              cursor: not-allowed;
              &.active {
                background: #dce5f3;
                color: #333333;
              }
            }
          }
          .tab {
            display: inline-block;
            font-size: 13px;
            color: @fontSubtitleColor;
            padding: 5px 12px;
            cursor: pointer;
            &:nth-child(1) {
              &.active {
                border-top-left-radius: 5px;
                border-bottom-left-radius: 5px;
              }
            }
            &:nth-child(2) {
              border-left: 1px solid #a5a5a5;
              border-right: 1px solid #a5a5a5;
            }
            &:nth-child(3) {
              &.active {
                border-top-right-radius: 5px;
                border-bottom-right-radius: 5px;
              }
            }
            &.active {
              color: #ffffff;
              background: @themeColor;
            }
          }
        }
      }
      .set-time-box {
        display: flex;
        align-items: center;
        margin: 30px 0;
        .title {
          font-size: 14px;
          color: @fontSubtitleColor;
          width: 80px;
          text-align: right;
          display: inline-block;
        }
        .time-select-box {
          .check-box {
            margin-left: 30px;
            .el-checkbox__label {
              color: @fontSubtitleColor;
              font-weight: normal;
              margin-right: 10px;
            }
          }
        }
      }
      .set-number {
        position: relative;
        // display: flex;
        .title {
          font-size: 14px;
          color: @fontSubtitleColor;
          width: 80px;
          text-align: right;
          display: inline-block;
        }
        .plan-time-box {
          background: #f5f5f5;
          border-radius: 5px;
          display: inline-block;
          margin-right: 10px;
          margin-bottom: 10px;
          text-align: center;
          font-size: 14px;
          padding: 10px;
          border-radius: 5px;
          .time {
            margin-bottom: 10px;
          }
        }
        .el-tag {
          //background: @themeColor;
          //color: #fff;
          margin: 10px 0;
        }

        .count-number {
          font-size: 16px;
          color: #333333;
          text-align: right;
          margin-right: 50px;
        }
        .el-collapse {
          border: none;
          padding-bottom: 10px;
          .is-active {
            .el-tag {
              background: @themeColor;
              color: #fff;
              margin: 10px 0;
            }
          }
        }
        .set-n-row {
          padding: 0 10px 10px 10px;
        }
        //.el-collapse{
        //  border: none;
        //}
      }
      .remark-box {
        margin-top: 20px;
        border-top: 1px dashed #e0e0e0;
        padding: 25px 0;
        .remark-example-box {
          .remark-example {
            color: @themeColor;
            border: 1px solid @themeColor;
            padding: 5px 15px;
            border-radius: 5px;
            font-size: 12px;
            cursor: pointer;
            display: inline-block;
            margin-right: 10px;
            margin-bottom: 10px;
          }
        }
        .textarea-box {
          font-size: 14px;
          color: @fontSubtitleColor;
          margin-top: 32px;
          .title {
            color: red;
          }
          .el-textarea {
            vertical-align: text-top;
          }
        }
      }
      .select-area-btn {
        width: 60%;
        text-align: left;
        overflow: hidden;
      }
      .price-text {
        display: inline-block;
        color: red;
        margin-left: 16px;
        font-size: 14px;
      }
      .tips {
        font-size: 14px;
        color: red;
      }
      .title {
        font-size: 14px;
        color: @fontSubtitleColor;
      }
      .check-content-box {
        font-size: 14px;
        color: @fontSubtitleColor;
        margin-top: 16px;
        .input {
          width: 200px;
          margin: 0 16px;
        }
      }
      .radio-box {
        margin-left: 16px;
      }
      .el-radio {
        color: @fontSubtitleColor;
        font-weight: normal;
      }
      .zpd-type-data {
        margin-top: 32px;
      }
    }
  }
  .page-footer {
    text-align: center;
    .show-pay-info-btn {
      background: @themeColor;
      color: #ffffff;
      font-size: 14px;
      height: 40px;
      width: 120px;
      line-height: 40px;
      padding: 0;
      margin-top: 16px;
    }
  }
  .select-goods-modal {
    /deep/ .el-dialog {
      .el-dialog__body {
        padding: 0 20px !important;
      }
    }
    .select-goods-modal-header {
      .el-form .el-form-item {
        padding-left: 0;
        padding-right: 15px;
        display: inline-flex;
        /deep/.el-form-item__content {
          width: 150px !important;
        }
        .inquire-btn {
          height: 32px !important;
          padding: 0px 10px !important;
          background: @themeColor;
          color: #ffffff;
          i {
            font-size: 14px;
          }
        }
      }
    }
    .select-goods-modal-content {
      max-height: 300px;
      overflow-y: scroll;
      .goods-img-box {
        width: 180px;
        display: inline-block;
        margin: 8px;
        cursor: pointer;
        border: 1px solid transparent;
        box-shadow: 0px 0px 3px #666;
        padding: 5px;
        border-radius: 3px;
        .text {
          font-size: 14px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .goods-img {
          width: 180px;
          height: 180px;
        }
      }
      .selectStyle {
        border: 1px solid red;
      }
    }
  }
  .area-dialog {
    .tips {
      color: red;
      margin: 0 10px 10px 0;
      font-size: 14px;
    }
    .area-content {
      border: 1px solid #e0e0e0;
      margin: 20px 10px 0 10px;
      /deep/ .el-checkbox__label {
        color: rgb(96, 98, 102) !important;
        font-weight: initial !important;
      }
      .province-select {
        padding: 10px 20px;
        border-bottom: 1px solid #e0e0e0;
      }
    }
    .left-box {
      display: inline-block;
      border-right: 1px solid #7d7d7d;
      margin-right: 15px;
      padding-right: 15px;
    }
    .save-btn {
      text-align: center;
      .el-button {
        border: 0px solid;
        padding: 0;
        height: 35px;
        line-height: 35px;
        width: 100px;
        background: @themeColor;
        color: #ffffff;
      }
    }
  }
  .pay-plan-dialog {
    .dialog-content {
      .card {
        display: flex;
        align-items: center;
        border: 1px solid #e0e0e0;
        border-radius: 3px;
        margin-bottom: 10px;

        .title {
          padding: 10px 16px;
          border: 1px solid #ecf5ff;
          width: 165px;
          text-align: left;
          background: #ecf5ff;
        }
        .content {
          padding: 11px 16px;
          border-left: 1px solid #e0e0e0;
          background: #ffffff;
          flex: 1;
        }
      }
    }
  }
  .no-data-img {
    text-align: center;
    margin-top: 80px;
    .tips {
      font-size: 14px;
      margin-top: 10px;
    }
  }
}
</style>
